package cn.iocoder.yudao.module.system.service.teacherdashboard;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.module.system.controller.admin.teacherdashboard.vo.*;
import cn.iocoder.yudao.module.system.dal.dataobject.examclass.ExamClassDO;
import cn.iocoder.yudao.module.system.dal.dataobject.examscore.ExamScoreDO;
import cn.iocoder.yudao.module.system.dal.dataobject.goal.StudentMajorGroupGoalDO;
import cn.iocoder.yudao.module.system.dal.dataobject.examtest.ExamTestDO;
import cn.iocoder.yudao.module.system.dal.mysql.examclass.ExamClassMapper;
import cn.iocoder.yudao.module.system.dal.mysql.examscore.ExamScoreMapper;
import cn.iocoder.yudao.module.system.dal.mysql.examtest.ExamTestMapper;
import cn.iocoder.yudao.module.system.service.permission.PermissionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.*;

/**
 * 教师看板 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Slf4j
public class TeacherDashboardServiceImpl implements TeacherDashboardService {

    @Resource
    private ExamScoreMapper examScoreMapper;
    
    @Resource
    private ExamTestMapper examTestMapper;
    
    @Resource
    private ExamClassMapper examClassMapper;
    
    @Resource
    private PermissionService permissionService;
    
    @Resource
    private cn.iocoder.yudao.module.system.service.gugu.MajorRecommendationService majorRecommendationService;
    
    @Resource
    private cn.iocoder.yudao.module.system.service.examcontrolline.ExamControlLineService examControlLineService;

    @Resource
    private cn.iocoder.yudao.module.system.service.scorelineconfig.ScoreLineConfigService scoreLineConfigService;

    @Resource
    private cn.iocoder.yudao.module.system.service.equivalentscorerank.EquivalentScoreRankService equivalentScoreRankService;

    @Resource
    private cn.iocoder.yudao.module.system.service.goal.StudentMajorGroupGoalService studentMajorGroupGoalService;

    @Override
    public TeacherDashboardRespVO getTeacherDashboard(@Valid TeacherDashboardReqVO reqVO) {
        log.info("获取教师看板数据，教师ID: {}, 班级ID: {}, 考试ID: {}", reqVO.getTeacherId(), reqVO.getClassId(), reqVO.getExamId());

        // 数据验证
        validateTeacherDashboardRequest(reqVO);

        TeacherDashboardRespVO respVO = new TeacherDashboardRespVO();
        
        // 检查是否为校领导且未传递班级ID（获取全考试数据）
        boolean isSchoolAdmin = permissionService.hasAnyRoles(reqVO.getTeacherId(), "school_admin");
        boolean isGlobalView = isSchoolAdmin && reqVO.getClassId() == null;

        if (isGlobalView) {
            // 校领导获取全考试数据
            return getGlobalExamDashboard(reqVO);
        } else {
            // 普通教师或校领导查看特定班级数据
            return getClassSpecificDashboard(reqVO);
        }
    }
    
    /**
     * 获取全考试看板数据（校领导专用）
     */
    private TeacherDashboardRespVO getGlobalExamDashboard(TeacherDashboardReqVO reqVO) {
        log.info("获取全考试看板数据，考试ID: {}", reqVO.getExamId());
        
        TeacherDashboardRespVO respVO = new TeacherDashboardRespVO();
        
        // 获取全考试班级信息（汇总信息）
        if (reqVO.getExamId() != null) {
            TeacherDashboardRespVO.ClassBasicInfo globalClassInfo = getGlobalClassInfo(reqVO.getExamId());
            respVO.setClassInfo(globalClassInfo != null ? globalClassInfo : createGlobalDefaultClassInfo(reqVO.getExamId()));
        }
        
        // 获取考试基本信息
        if (reqVO.getExamId() != null) {
            TeacherDashboardRespVO.LatestExamOverview examOverview = getGlobalExamOverview(reqVO.getExamId());
            respVO.setLatestExam(examOverview != null ? examOverview : createDefaultExamOverview(reqVO.getExamId()));
        }
        
        // 获取全考试成绩统计
        if (Boolean.TRUE.equals(reqVO.getIncludeScoreStatistics()) && reqVO.getExamId() != null) {
            TeacherDashboardRespVO.ScoreStatistics scoreStats = getGlobalScoreStatistics(reqVO.getExamId());
            respVO.setScoreStatistics(scoreStats != null ? scoreStats : createDefaultScoreStatistics());
        }
        
        // 获取全考试升学分析
        if (Boolean.TRUE.equals(reqVO.getIncludeAdmissionAnalysis()) && reqVO.getExamId() != null) {
            TeacherDashboardRespVO.AdmissionAnalysis admissionAnalysis = getGlobalAdmissionAnalysis(reqVO.getExamId());
            respVO.setAdmissionAnalysis(admissionAnalysis != null ? admissionAnalysis : createDefaultAdmissionAnalysis());
        }
        
        // 获取全考试学生排名信息
        if (Boolean.TRUE.equals(reqVO.getIncludeStudentRanking()) && reqVO.getExamId() != null) {
            TeacherDashboardRespVO.StudentRankingInfo studentRanking = getGlobalStudentRanking(reqVO.getExamId());
            respVO.setStudentRanking(studentRanking != null ? studentRanking : createDefaultStudentRanking());
        }
        
        // 获取全考试对比分析
        if (Boolean.TRUE.equals(reqVO.getIncludeComparison()) && reqVO.getExamId() != null) {
            TeacherDashboardRespVO.ComparisonAnalysis comparison = getGlobalComparisonAnalysis(reqVO.getExamId());
            respVO.setComparison(comparison != null ? comparison : createDefaultComparison());
        }
        
        // 获取全考试重点关注学生
        if (reqVO.getExamId() != null) {
            List<TeacherDashboardRespVO.FocusStudent> focusStudents = getGlobalFocusStudents(reqVO.getExamId());
            respVO.setFocusStudents(focusStudents != null ? focusStudents : new ArrayList<>());
        } else {
            respVO.setFocusStudents(new ArrayList<>());
        }
        
        // 生成全考试教学建议
        if (reqVO.getExamId() != null) {
            List<TeacherDashboardRespVO.TeachingSuggestion> suggestions = generateGlobalTeachingSuggestions(reqVO.getExamId());
            respVO.setTeachingSuggestions(suggestions != null ? suggestions : createDefaultTeachingSuggestions());
        } else {
            respVO.setTeachingSuggestions(createDefaultTeachingSuggestions());
        }

        // 获取全考试学生目标汇总
        if (reqVO.getExamId() != null) {
            respVO.setStudentGoalSummary(getStudentGoalSummary(null, reqVO.getExamId()));
            respVO.setGoalIndicatorAnalysis(getGoalIndicatorAnalysis(null, reqVO.getExamId()));
        }
        
        return respVO;
    }
    
    /**
     * 获取特定班级看板数据
     */
    private TeacherDashboardRespVO getClassSpecificDashboard(TeacherDashboardReqVO reqVO) {
        TeacherDashboardRespVO respVO = new TeacherDashboardRespVO();

        // 获取班级基本信息（必需数据，提供默认值）
        if (reqVO.getClassId() != null) {
            TeacherDashboardRespVO.ClassBasicInfo classInfo = getClassBasicInfo(reqVO.getClassId());
            respVO.setClassInfo(classInfo != null ? classInfo : createDefaultClassInfo(reqVO.getClassId()));
        }

        // 获取最新考试概况（核心数据，提供默认值）
        if (reqVO.getExamId() != null && reqVO.getClassId() != null) {
            TeacherDashboardRespVO.LatestExamOverview latestExam = getLatestExamOverview(reqVO.getClassId(), reqVO.getExamId());
            respVO.setLatestExam(latestExam != null ? latestExam : createDefaultExamOverview(reqVO.getExamId()));
        }

        // 获取成绩统计（提供默认值）
        if (Boolean.TRUE.equals(reqVO.getIncludeScoreStatistics()) && reqVO.getClassId() != null && reqVO.getExamId() != null) {
            TeacherDashboardRespVO.ScoreStatistics scoreStats = getClassScoreStatistics(reqVO.getClassId(), reqVO.getExamId());
            respVO.setScoreStatistics(scoreStats != null ? scoreStats : createDefaultScoreStatistics());
        }

        // 获取升学分析（提供默认值）
        if (Boolean.TRUE.equals(reqVO.getIncludeAdmissionAnalysis()) && reqVO.getClassId() != null && reqVO.getExamId() != null) {
            TeacherDashboardRespVO.AdmissionAnalysis admissionAnalysis = getAdmissionAnalysisInfo(reqVO.getClassId(), reqVO.getExamId());
            respVO.setAdmissionAnalysis(admissionAnalysis != null ? admissionAnalysis : createDefaultAdmissionAnalysis());
        }

        // 获取学生排名信息（提供默认值）
        if (Boolean.TRUE.equals(reqVO.getIncludeStudentRanking()) && reqVO.getClassId() != null && reqVO.getExamId() != null) {
            TeacherDashboardRespVO.StudentRankingInfo studentRanking = getStudentRankingInfo(reqVO.getClassId(), reqVO.getExamId());
            respVO.setStudentRanking(studentRanking != null ? studentRanking : createDefaultStudentRanking());
        }

        // 获取对比分析（提供默认值）
        if (Boolean.TRUE.equals(reqVO.getIncludeComparison()) && reqVO.getClassId() != null && reqVO.getExamId() != null) {
            TeacherDashboardRespVO.ComparisonAnalysis comparison = getComparisonAnalysis(reqVO.getClassId(), reqVO.getExamId());
            respVO.setComparison(comparison != null ? comparison : createDefaultComparison());
        }

        // 获取重点关注学生（确保不为null）
        if (reqVO.getClassId() != null && reqVO.getExamId() != null) {
            List<TeacherDashboardRespVO.FocusStudent> focusStudents = getFocusStudents(reqVO.getClassId(), reqVO.getExamId());
            respVO.setFocusStudents(focusStudents != null ? focusStudents : new ArrayList<>());
        } else {
            respVO.setFocusStudents(new ArrayList<>());
        }

        // 生成教学建议（确保不为null）
        if (reqVO.getClassId() != null && reqVO.getExamId() != null) {
            List<TeacherDashboardRespVO.TeachingSuggestion> suggestions = generateTeachingSuggestions(reqVO.getClassId(), reqVO.getExamId());
            respVO.setTeachingSuggestions(suggestions != null ? suggestions : createDefaultTeachingSuggestions());
        } else {
            respVO.setTeachingSuggestions(createDefaultTeachingSuggestions());
        }

        // 获取学生目标汇总
        if (reqVO.getClassId() != null && reqVO.getExamId() != null) {
            respVO.setStudentGoalSummary(getStudentGoalSummary(reqVO.getClassId(), reqVO.getExamId()));
            respVO.setGoalIndicatorAnalysis(getGoalIndicatorAnalysis(reqVO.getClassId(), reqVO.getExamId()));
        }

        return respVO;
    }
    
    // ==================== 全考试数据获取方法（校领导专用） ====================
    
    /**
     * 获取全考试概况
     */
    private TeacherDashboardRespVO.LatestExamOverview getGlobalExamOverview(Long examId) {
        ExamTestDO examTest = examTestMapper.selectById(examId);
        if (examTest == null) {
            return null;
        }

        TeacherDashboardRespVO.LatestExamOverview overview = new TeacherDashboardRespVO.LatestExamOverview();
        overview.setExamId(examTest.getId());
        overview.setExamName(examTest.getExamName());
        overview.setExamDate(examTest.getExamDate());

        // 获取全考试统计信息（所有班级）
        Map<String, Object> globalStats = examScoreMapper.selectGradeStatistics(examId);
        if (globalStats != null) {
            overview.setClassAvgScore(getBigDecimalFromMap(globalStats, "avgScore"));
            overview.setClassMaxScore(getBigDecimalFromMap(globalStats, "maxScore"));
            overview.setClassMinScore(getBigDecimalFromMap(globalStats, "minScore"));
            
            // 参考人数 = 总人数
            Object totalCountObj = globalStats.get("totalStudents");
            if (totalCountObj != null && totalCountObj instanceof Number) {
                int totalCount = ((Number) totalCountObj).intValue();
                overview.setParticipantCount(totalCount);
                overview.setAbsentCount(0); // 简化处理
            }
        }

        // 全考试视图下，年级平均分就是整体平均分
        overview.setGradeAvgScore(overview.getClassAvgScore());
        
        // 获取总班级数
        Integer totalClasses = examScoreMapper.selectTotalClassesInGrade(null, examId);
        overview.setTotalClassesInGrade(totalClasses);
        overview.setClassRankInGrade(1); // 全考试视图下排名为1

        return overview;
    }
    
    /**
     * 获取全考试成绩统计
     */
    private TeacherDashboardRespVO.ScoreStatistics getGlobalScoreStatistics(Long examId) {
        TeacherDashboardRespVO.ScoreStatistics statistics = new TeacherDashboardRespVO.ScoreStatistics();
        
        // 获取全考试总分统计
        Map<String, Object> globalStats = examScoreMapper.selectGradeStatistics(examId);
        if (globalStats != null) {
            TeacherDashboardRespVO.TotalScoreStats totalScoreStats = new TeacherDashboardRespVO.TotalScoreStats();
            totalScoreStats.setAvgScore(getBigDecimalFromMap(globalStats, "avgScore"));
            totalScoreStats.setMaxScore(getBigDecimalFromMap(globalStats, "maxScore"));
            totalScoreStats.setMinScore(getBigDecimalFromMap(globalStats, "minScore"));
            totalScoreStats.setStandardDeviation(getBigDecimalFromMap(globalStats, "standardDeviation"));
            totalScoreStats.setGradeAvgDiff(BigDecimal.ZERO); // 全考试视图下差值为0
            totalScoreStats.setGradeRank(1); // 全考试视图下排名为1
            statistics.setTotalScore(totalScoreStats);
        }

        // 获取全考试各科成绩统计
        Map<String, TeacherDashboardRespVO.SubjectScoreStats> subjectScores = getGlobalSubjectScoreStats(examId);
        statistics.setSubjectScores(subjectScores);
        
        return statistics;
    }
    
    /**
     * 获取全考试各科成绩统计
     */
    private Map<String, TeacherDashboardRespVO.SubjectScoreStats> getGlobalSubjectScoreStats(Long examId) {
        Map<String, TeacherDashboardRespVO.SubjectScoreStats> subjectScores = new HashMap<>();
        
        // 获取全考试各科成绩统计（聚合所有班级数据）
        List<ExamScoreDO> allScores = examScoreMapper.selectList(new LambdaQueryWrapperX<ExamScoreDO>()
                .eq(ExamScoreDO::getExamId, examId));
        
        if (!allScores.isEmpty()) {
            // 语文统计
            subjectScores.put("语文", calculateSubjectStats(allScores, "语文", 
                score -> score.getChineseScore(), 150.0));
            
            // 数学统计
            subjectScores.put("数学", calculateSubjectStats(allScores, "数学", 
                score -> score.getMathScore(), 150.0));
            
            // 英语统计
            subjectScores.put("英语", calculateSubjectStats(allScores, "英语", 
                score -> score.getEnglishScore(), 150.0));
            
            // 物理统计
            subjectScores.put("物理", calculateSubjectStats(allScores, "物理", 
                score -> score.getPhysicsScore(), 100.0));
            
            // 化学统计
            subjectScores.put("化学", calculateSubjectStats(allScores, "化学", 
                score -> score.getChemistryScore(), 100.0));
            
            // 生物统计
            subjectScores.put("生物", calculateSubjectStats(allScores, "生物", 
                score -> score.getBiologyScore(), 100.0));
            
            // 政治统计
            subjectScores.put("政治", calculateSubjectStats(allScores, "政治", 
                score -> score.getPoliticsScore(), 100.0));
            
            // 历史统计
            subjectScores.put("历史", calculateSubjectStats(allScores, "历史", 
                score -> score.getHistoryScore(), 100.0));
            
            // 地理统计
            subjectScores.put("地理", calculateSubjectStats(allScores, "地理", 
                score -> score.getGeographyScore(), 100.0));
        }
        
        return subjectScores;
    }
    
    /**
     * 计算单科成绩统计
     */
    private TeacherDashboardRespVO.SubjectScoreStats calculateSubjectStats(
            List<ExamScoreDO> allScores, String subjectName, 
            java.util.function.Function<ExamScoreDO, BigDecimal> scoreExtractor, Double fullScore) {
        
        TeacherDashboardRespVO.SubjectScoreStats stats = new TeacherDashboardRespVO.SubjectScoreStats();
        stats.setSubjectName(subjectName);
        
        List<BigDecimal> validScores = allScores.stream()
                .map(scoreExtractor)
                .filter(Objects::nonNull)
                .collect(Collectors.toList());
        
        if (!validScores.isEmpty()) {
            // 计算平均分
            BigDecimal avgScore = validScores.stream()
                    .reduce(BigDecimal.ZERO, BigDecimal::add)
                    .divide(BigDecimal.valueOf(validScores.size()), 2, RoundingMode.HALF_UP);
            stats.setAvgScore(avgScore);
            
            // 计算最高分和最低分
            stats.setMaxScore(validScores.stream().max(BigDecimal::compareTo).orElse(BigDecimal.ZERO));
            stats.setMinScore(validScores.stream().min(BigDecimal::compareTo).orElse(BigDecimal.ZERO));
            
            // 计算及格率（60%为及格线）
            BigDecimal passLine = BigDecimal.valueOf(fullScore * 0.6);
            long passCount = validScores.stream()
                    .mapToLong(score -> score.compareTo(passLine) >= 0 ? 1 : 0)
                    .sum();
            BigDecimal passRate = BigDecimal.valueOf(passCount * 100.0 / validScores.size())
                    .setScale(2, RoundingMode.HALF_UP);
            stats.setPassRate(passRate);
            
            // 计算优秀率（85%为优秀线）
            BigDecimal excellentLine = BigDecimal.valueOf(fullScore * 0.85);
            long excellentCount = validScores.stream()
                    .mapToLong(score -> score.compareTo(excellentLine) >= 0 ? 1 : 0)
                    .sum();
            BigDecimal excellentRate = BigDecimal.valueOf(excellentCount * 100.0 / validScores.size())
                    .setScale(2, RoundingMode.HALF_UP);
            stats.setExcellentRate(excellentRate);
            
            // 全考试视图下年级差值为0，排名为1
            stats.setGradeAvgDiff(BigDecimal.ZERO);
            stats.setGradeRank(1);
        } else {
            // 没有有效成绩时的默认值
            stats.setAvgScore(BigDecimal.ZERO);
            stats.setMaxScore(BigDecimal.ZERO);
            stats.setMinScore(BigDecimal.ZERO);
            stats.setPassRate(BigDecimal.ZERO);
            stats.setExcellentRate(BigDecimal.ZERO);
            stats.setGradeAvgDiff(BigDecimal.ZERO);
            stats.setGradeRank(1);
        }
        
        return stats;
    }
    
    /**
     * 获取全考试升学分析
     */
    private TeacherDashboardRespVO.AdmissionAnalysis getGlobalAdmissionAnalysis(Long examId) {
        // 使用年级统计作为全考试分析
        return getAdmissionAnalysisInfo(null, examId);
    }
    
    /**
     * 获取全考试学生排名
     */
    private TeacherDashboardRespVO.StudentRankingInfo getGlobalStudentRanking(Long examId) {
        TeacherDashboardRespVO.StudentRankingInfo rankingInfo = new TeacherDashboardRespVO.StudentRankingInfo();
        
        // 获取全考试前10名学生（跨班级）
        List<TeacherDashboardRespVO.TopStudentInfo> topStudents = getGlobalTopStudents(examId, 10);
        rankingInfo.setTopStudents(topStudents);
        
        return rankingInfo;
    }
    
    /**
     * 获取全考试前N名学生
     */
    private List<TeacherDashboardRespVO.TopStudentInfo> getGlobalTopStudents(Long examId, Integer topN) {
        // 获取全考试前N名学生（使用年级排名查询）
        List<ExamScoreDO> topScores = examScoreMapper.selectList(new LambdaQueryWrapperX<ExamScoreDO>()
                .eq(ExamScoreDO::getExamId, examId)
                .orderByDesc(ExamScoreDO::getTotalScore)
                .last("LIMIT " + topN));
        
        List<TeacherDashboardRespVO.TopStudentInfo> topStudents = new ArrayList<>();
        for (ExamScoreDO scoreData : topScores) {
            TeacherDashboardRespVO.TopStudentInfo student = new TeacherDashboardRespVO.TopStudentInfo();
            student.setStudentId(scoreData.getStudentId());
            student.setStudentName(scoreData.getStudentName());
            student.setStudentNo(scoreData.getStudentNo());
            student.setClassName(scoreData.getClassName());
            student.setTotalScore(scoreData.getTotalScore());
            student.setClassRank(scoreData.getClassRank());
            student.setGradeRank(scoreData.getGradeRank());
            student.setSubjectCombination(scoreData.getSubjectCombination());
            student.setFirstSubject(scoreData.getFirstSubject());
            student.setSecondSubject(scoreData.getSecondSubject());
            student.setExamType(scoreData.getExamType());
            
            // 设置其他字段
            student.setTotalScoreAssigned(scoreData.getTotalScoreAssigned());
            student.setCombinationRank(scoreData.getCombinationRank());
            student.setSchoolRank(scoreData.getSchoolRank());
            student.setTotalUnionRank(scoreData.getTotalUnionRank());
            
            // 根据分数预测升学层次
            if (student.getTotalScore() != null) {
                student.setPredictedAdmissionLevel(getAdmissionLevel(student.getTotalScore()));
            }
            
            // 根据预测层次设置目标院校
            String level = student.getPredictedAdmissionLevel();
            if ("985".equals(level)) {
                student.setTargetUniversity("清华大学/北京大学");
            } else if ("211".equals(level)) {
                student.setTargetUniversity("中山大学/华南理工大学");
            } else if ("一本".equals(level)) {
                student.setTargetUniversity("深圳大学/广东工业大学");
            } else if ("二本".equals(level)) {
                student.setTargetUniversity("广东财经大学/广州大学");
            } else {
                student.setTargetUniversity("广东轻工职业技术学院");
            }
            
            topStudents.add(student);
        }
        
        return topStudents;
    }
    
    /**
     * 获取全考试对比分析
     */
    private TeacherDashboardRespVO.ComparisonAnalysis getGlobalComparisonAnalysis(Long examId) {
        TeacherDashboardRespVO.ComparisonAnalysis analysis = new TeacherDashboardRespVO.ComparisonAnalysis();
        
        // 获取全考试统计信息作为对比基准
        Map<String, Object> globalStats = examScoreMapper.selectGradeStatistics(examId);
        TeacherDashboardRespVO.ClassComparisonInfo classComparison = new TeacherDashboardRespVO.ClassComparisonInfo();
        
        // 全考试视图下的对比信息
        if (globalStats != null) {
            Object totalStudentsObj = globalStats.get("totalStudents");
            if (totalStudentsObj != null) {
                classComparison.setTotalClasses(((Number) totalStudentsObj).intValue() / 45); // 假设平均每班45人
            }
        }
        
        classComparison.setGradeRank(1); // 全考试视图下排名为1
        classComparison.setAvgScoreRank(1);
        classComparison.setFirstTierRateRank(1);
        analysis.setClassComparison(classComparison);
        
        return analysis;
    }
    
    /**
     * 获取全考试重点关注学生
     */
    private List<TeacherDashboardRespVO.FocusStudent> getGlobalFocusStudents(Long examId) {
        // 获取全考试范围内的重点关注学生
        return getFocusStudents(null, examId);
    }
    
    /**
     * 生成全考试教学建议
     */
    private List<TeacherDashboardRespVO.TeachingSuggestion> generateGlobalTeachingSuggestions(Long examId) {
        // 生成全考试范围的教学建议
        return generateTeachingSuggestions(null, examId);
    }
    
    /**
     * 获取全考试升学预测统计
     */
    private TeacherDashboardRespVO.AdmissionPredictionStats getGlobalAdmissionPredictionStats(Long examId) {
        // 获取全考试所有学生成绩
        List<ExamScoreDO> allScores = examScoreMapper.selectList(new LambdaQueryWrapperX<ExamScoreDO>()
                .eq(ExamScoreDO::getExamId, examId)
                .orderByDesc(ExamScoreDO::getTotalScore));
        
        if (allScores.isEmpty()) {
            return new TeacherDashboardRespVO.AdmissionPredictionStats();
        }
        
        TeacherDashboardRespVO.AdmissionPredictionStats stats = new TeacherDashboardRespVO.AdmissionPredictionStats();
        int totalStudents = allScores.size();
        
        // 分类统计学生
        List<TeacherDashboardRespVO.AdmissionStudentInfo> predicted985Students = new ArrayList<>();
        List<TeacherDashboardRespVO.AdmissionStudentInfo> predicted211Students = new ArrayList<>();
        List<TeacherDashboardRespVO.AdmissionStudentInfo> predictedDoubleFirstClassStudents = new ArrayList<>();
        List<TeacherDashboardRespVO.AdmissionStudentInfo> predictedSpecialControlStudents = new ArrayList<>();
        List<TeacherDashboardRespVO.AdmissionStudentInfo> predictedUndergraduateStudents = new ArrayList<>();
        List<TeacherDashboardRespVO.AdmissionStudentInfo> predictedSpecialtyStudents = new ArrayList<>();
        List<TeacherDashboardRespVO.AdmissionStudentInfo> belowLineStudents = new ArrayList<>();
        
        // 计算等效位次并分类学生
        for (int i = 0; i < allScores.size(); i++) {
            ExamScoreDO score = allScores.get(i);
            if (score.getTotalScore() == null) continue;
            
            // 确定学生的考试类型
            String examType = determineExamType(score);
            
            // 根据考试类型获取对应的特控线和省控线
            BigDecimal controlLineScore = getExamControlLineScore(examId, examType);
            BigDecimal provinceControlLineScore = getProvinceControlLineScore(examType);
            
            // 计算2025等效位次（基于特控线和省控线）
            int equivalentRanking2025 = calculateEquivalentRanking2025(score, controlLineScore, provinceControlLineScore);
            
            TeacherDashboardRespVO.AdmissionStudentInfo studentInfo = createAdmissionStudentInfo(score, equivalentRanking2025);
            
            // 计算等效分用于分类判断
            BigDecimal equivalentScore = score.getTotalScore().subtract(controlLineScore).add(provinceControlLineScore);
            
            // 获取动态分数线配置
            Map<String, Integer> scoreLineConfig = getScoreLineConfig(examType);
            int score985 = scoreLineConfig.get("score985");
            int score211 = scoreLineConfig.get("score211");
            int scoreDoubleFirst = scoreLineConfig.get("scoreDoubleFirst");
            int scoreSpecialControl = scoreLineConfig.get("scoreSpecialControl");
            int scoreUndergraduate = scoreLineConfig.get("scoreUndergraduate");
            int scoreSpecialist = scoreLineConfig.get("scoreSpecialist");
            
            // 根据等效分进行分数线分类学生
            if (equivalentScore.compareTo(BigDecimal.valueOf(score985)) >= 0) {
                predicted985Students.add(studentInfo);
                predicted211Students.add(studentInfo);
                predictedDoubleFirstClassStudents.add(studentInfo);
                predictedSpecialControlStudents.add(studentInfo);
                predictedUndergraduateStudents.add(studentInfo);
                predictedSpecialtyStudents.add(studentInfo);
            } else if (equivalentScore.compareTo(BigDecimal.valueOf(score211)) >= 0) {
                predicted211Students.add(studentInfo);
                predictedDoubleFirstClassStudents.add(studentInfo);
                predictedSpecialControlStudents.add(studentInfo);
                predictedUndergraduateStudents.add(studentInfo);
                predictedSpecialtyStudents.add(studentInfo);
            } else if (equivalentScore.compareTo(BigDecimal.valueOf(scoreDoubleFirst)) >= 0) {
                predictedDoubleFirstClassStudents.add(studentInfo);
                predictedSpecialControlStudents.add(studentInfo);
                predictedUndergraduateStudents.add(studentInfo);
                predictedSpecialtyStudents.add(studentInfo);
            } else if (equivalentScore.compareTo(BigDecimal.valueOf(scoreSpecialControl)) >= 0) {
                predictedSpecialControlStudents.add(studentInfo);
                predictedUndergraduateStudents.add(studentInfo);
                predictedSpecialtyStudents.add(studentInfo);
            } else if (equivalentScore.compareTo(BigDecimal.valueOf(scoreUndergraduate)) >= 0) {
                predictedUndergraduateStudents.add(studentInfo);
                predictedSpecialtyStudents.add(studentInfo);
            } else if (equivalentScore.compareTo(BigDecimal.valueOf(scoreSpecialist)) >= 0) {
                predictedSpecialtyStudents.add(studentInfo);
            } else {
                belowLineStudents.add(studentInfo);
            }
        }
        
        // 设置统计数据
        stats.setPredicted985Count(predicted985Students.size());
        stats.setPredicted985Rate(calculateRate(predicted985Students.size(), totalStudents));
        stats.setPredicted985Students(predicted985Students);
        
        stats.setPredicted211Count(predicted211Students.size());
        stats.setPredicted211Rate(calculateRate(predicted211Students.size(), totalStudents));
        stats.setPredicted211Students(predicted211Students);
        
        stats.setPredictedDoubleFirstClassCount(predictedDoubleFirstClassStudents.size());
        stats.setPredictedDoubleFirstClassRate(calculateRate(predictedDoubleFirstClassStudents.size(), totalStudents));
        stats.setPredictedDoubleFirstClassStudents(predictedDoubleFirstClassStudents);
        
        stats.setPredictedSpecialControlCount(predictedSpecialControlStudents.size());
        stats.setPredictedSpecialControlRate(calculateRate(predictedSpecialControlStudents.size(), totalStudents));
        stats.setPredictedSpecialControlStudents(predictedSpecialControlStudents);
        
        stats.setPredictedUndergraduateCount(predictedUndergraduateStudents.size());
        stats.setPredictedUndergraduateRate(calculateRate(predictedUndergraduateStudents.size(), totalStudents));
        stats.setPredictedUndergraduateStudents(predictedUndergraduateStudents);
        
        stats.setPredictedSpecialtyCount(predictedSpecialtyStudents.size());
        stats.setPredictedSpecialtyRate(calculateRate(predictedSpecialtyStudents.size(), totalStudents));
        stats.setPredictedSpecialtyStudents(predictedSpecialtyStudents);
        
        stats.setBelowLineCount(belowLineStudents.size());
        stats.setBelowLineRate(calculateRate(belowLineStudents.size(), totalStudents));
        stats.setBelowLineStudents(belowLineStudents);
        
        // 设置兼容性字段
        stats.setPredictedFirstTierCount(predictedSpecialControlStudents.size());
        stats.setPredictedFirstTierRate(stats.getPredictedSpecialControlRate());
        stats.setPredictedSecondTierCount(predictedUndergraduateStudents.size());
        stats.setPredictedSecondTierRate(stats.getPredictedUndergraduateRate());
        
        return stats;
    }
    
    /**
     * 计算2025等效位次
     * 使用系统已有的等效位次计算服务
     */
    private int calculateEquivalentRanking2025(ExamScoreDO score, BigDecimal controlLineScore, BigDecimal provinceControlLineScore) {
        try {
            // 使用系统已有的等效分计算方法
            BigDecimal equivalentScore = score.getTotalScore().subtract(controlLineScore).add(provinceControlLineScore);
            
            // 确定考试类型
            String examType = determineExamType(score);
            
            // 使用系统已有的等效位次计算服务
            return majorRecommendationService.calculateRankByScore(
                    equivalentScore.intValue(), 
                    "安徽", 
                    2025, 
                    examType
            );
        } catch (Exception e) {
            log.error("计算等效位次失败：score={}, controlLineScore={}, provinceControlLineScore={}", 
                    score.getTotalScore(), controlLineScore, provinceControlLineScore, e);
            // 如果计算失败，返回一个基于分数的估算位次
            return estimateRankByScore(score.getTotalScore());
        }
    }
    
    /**
     * 根据成绩判断考试类型
     */
    private String determineExamType(ExamScoreDO examScore) {
        // 根据首选科目判断考试类型
        String firstSubject = examScore.getFirstSubject();
        if ("物理".equals(firstSubject)) {
            return "物理类";
        } else if ("历史".equals(firstSubject)) {
            return "历史类";
        }
        
        // 如果无法从首选科目判断，尝试从选科组合判断
        String subjectCombination = examScore.getSubjectCombination();
        if (subjectCombination != null) {
            if (subjectCombination.contains("物理")) {
                return "物理类";
            } else if (subjectCombination.contains("历史")) {
                return "历史类";
            }
        }
        
        // 默认返回物理类
        return "物理类";
    }
    
    /**
     * 基于分数估算位次（备用方法）
     */
    private int estimateRankByScore(BigDecimal score) {
        // 简单的分数-位次估算
        if (score.compareTo(BigDecimal.valueOf(680)) >= 0) {
            return 5000; // 高分段
        } else if (score.compareTo(BigDecimal.valueOf(650)) >= 0) {
            return 15000;
        } else if (score.compareTo(BigDecimal.valueOf(620)) >= 0) {
            return 30000;
        } else if (score.compareTo(BigDecimal.valueOf(580)) >= 0) {
            return 60000;
        } else if (score.compareTo(BigDecimal.valueOf(520)) >= 0) {
            return 120000;
        } else {
            return 200000;
        }
    }
    
    /**
     * 创建升学预测学生信息
     */
    private TeacherDashboardRespVO.AdmissionStudentInfo createAdmissionStudentInfo(ExamScoreDO score, int equivalentRanking2025) {
        TeacherDashboardRespVO.AdmissionStudentInfo studentInfo = new TeacherDashboardRespVO.AdmissionStudentInfo();
        
        studentInfo.setStudentId(score.getStudentId());
        studentInfo.setStudentName(score.getStudentName());
        studentInfo.setStudentNo(score.getStudentNo());
        studentInfo.setClassId(score.getClassId());
        studentInfo.setClassName(score.getClassName());
        studentInfo.setCurrentScore(score.getTotalScore());
        studentInfo.setEquivalentRanking2025(equivalentRanking2025);
        studentInfo.setSubjectCombination(score.getSubjectCombination());
        studentInfo.setFirstSubject(score.getFirstSubject());
        studentInfo.setSecondSubject(score.getSecondSubject());
        studentInfo.setExamType(score.getExamType());
        
        // 根据等效位次预测升学层次
        String admissionLevel = predictAdmissionLevel(equivalentRanking2025);
        studentInfo.setPredictedAdmissionLevel(admissionLevel);
        
        // 根据位次计算可报考院校
        studentInfo.setEligible985Universities(getEligible985Universities(equivalentRanking2025));
        studentInfo.setEligible211Universities(getEligible211Universities(equivalentRanking2025));
        studentInfo.setEligibleDoubleFirstClassUniversities(getEligibleDoubleFirstClassUniversities(equivalentRanking2025));
        
        return studentInfo;
    }
    
    /**
     * 根据等效位次预测升学层次（基于安徽省2025年实际录取数据）
     */
    private String predictAdmissionLevel(int equivalentRanking2025) {
        if (equivalentRanking2025 <= 27000) {
            return "985"; // 985院校最低位次27000（物理类606分）
        } else if (equivalentRanking2025 <= 60000) {
            return "211"; // 211院校物理类550分以上，历史类520分以上
        } else if (equivalentRanking2025 <= 80000) {
            return "双一流"; // 省内211高校580分以上
        } else if (equivalentRanking2025 <= 120000) {
            return "特控线"; // 特控线518分
        } else if (equivalentRanking2025 <= 280000) {
            return "本科线"; // 本科线440分
        } else if (equivalentRanking2025 <= 450000) {
            return "专科";
        } else {
            return "未达线";
        }
    }
    
    /**
     * 获取可报考的985院校（基于安徽省2025年实际录取数据）
     */
    private List<String> getEligible985Universities(int equivalentRanking2025) {
        List<String> all985 = cn.iocoder.yudao.module.system.enums.UniversityTypeEnum.get985Universities();
        
        if (equivalentRanking2025 <= 300) {
            return all985; // 前300名可以冲刺所有985（热门专业需690分以上）
        } else if (equivalentRanking2025 <= 5000) {
            return all985.subList(0, Math.min(25, all985.size())); // 前5000名可以报考大部分985
        } else if (equivalentRanking2025 <= 27000) {
            return all985.subList(0, Math.min(15, all985.size())); // 前27000名可以报考部分985（最低录取位次）
        } else {
            return new ArrayList<>(); // 27000名以后基本无法报考985
        }
    }
    
    /**
     * 获取可报考的211院校（基于安徽省2025年实际录取数据）
     */
    private List<String> getEligible211Universities(int equivalentRanking2025) {
        List<String> all211 = cn.iocoder.yudao.module.system.enums.UniversityTypeEnum.get211Universities();
        
        if (equivalentRanking2025 <= 10000) {
            return all211; // 前10000名可以报考所有211
        } else if (equivalentRanking2025 <= 35000) {
            return all211.subList(0, Math.min(60, all211.size())); // 前35000名可以报考大部分211
        } else if (equivalentRanking2025 <= 60000) {
            return all211.subList(0, Math.min(30, all211.size())); // 前60000名可以报考部分211（物理类550分，历史类520分）
        } else {
            return new ArrayList<>(); // 60000名以后基本无法报考211
        }
    }
    
    /**
     * 获取可报考的双一流院校（基于安徽省2025年实际录取数据）
     */
    private List<String> getEligibleDoubleFirstClassUniversities(int equivalentRanking2025) {
        List<String> allDoubleFirst = cn.iocoder.yudao.module.system.enums.UniversityTypeEnum.getDoubleFirstClassUniversities();
        
        if (equivalentRanking2025 <= 15000) {
            return allDoubleFirst; // 前15000名可以报考所有双一流
        } else if (equivalentRanking2025 <= 50000) {
            return allDoubleFirst.subList(0, Math.min(70, allDoubleFirst.size())); // 前50000名可以报考大部分双一流
        } else if (equivalentRanking2025 <= 80000) {
            return allDoubleFirst.subList(0, Math.min(40, allDoubleFirst.size())); // 前80000名可以报考部分双一流（省内211标准580分）
        } else {
            return new ArrayList<>(); // 80000名以后基本无法报考双一流
        }
    }
    
    /**
     * 计算百分比
     */
    private BigDecimal calculateRate(int count, int total) {
        if (total == 0) {
            return BigDecimal.ZERO;
        }
        return BigDecimal.valueOf(count * 100.0 / total).setScale(2, RoundingMode.HALF_UP);
    }
    
    /**
     * 获取考试的特控线分数（默认物理类）
     */
    private BigDecimal getExamControlLineScore(Long examId) {
        try {
            // 查询该考试的特控线配置
            List<cn.iocoder.yudao.module.system.dal.dataobject.examcontrolline.ExamControlLineDO> controlLines = 
                    examControlLineService.getExamControlLineListByExamId(examId);
            
            if (!controlLines.isEmpty()) {
                cn.iocoder.yudao.module.system.dal.dataobject.examcontrolline.ExamControlLineDO controlLine = controlLines.get(0);
                // 优先使用物理类分数线，其次历史类，最后使用通用分数线
                if (controlLine.getPhysicsScoreLine() != null) {
                    return controlLine.getPhysicsScoreLine();
                } else if (controlLine.getHistoryScoreLine() != null) {
                    return controlLine.getHistoryScoreLine();
                } else {
                    return controlLine.getScoreLine();
                }
            }
        } catch (Exception e) {
            log.error("获取考试特控线失败：examId={}", examId, e);
        }
        
        // 如果没有配置特控线，使用默认值（安徽省2025年特控线预估）
        return BigDecimal.valueOf(518);
    }
    
    /**
     * 根据考试类型获取考试的特控线分数
     */
    private BigDecimal getExamControlLineScore(Long examId, String examType) {
        try {
            // 查询该考试的特控线配置
            List<cn.iocoder.yudao.module.system.dal.dataobject.examcontrolline.ExamControlLineDO> controlLines = 
                    examControlLineService.getExamControlLineListByExamId(examId);
            
            if (!controlLines.isEmpty()) {
                cn.iocoder.yudao.module.system.dal.dataobject.examcontrolline.ExamControlLineDO controlLine = controlLines.get(0);
                // 根据考试类型返回对应的特控线
                if ("历史类".equals(examType)) {
                    if (controlLine.getHistoryScoreLine() != null) {
                        return controlLine.getHistoryScoreLine();
                    }
                } else if ("物理类".equals(examType)) {
                    if (controlLine.getPhysicsScoreLine() != null) {
                        return controlLine.getPhysicsScoreLine();
                    }
                }
                // 如果没有对应类型的特控线，使用通用分数线
                if (controlLine.getScoreLine() != null) {
                    return controlLine.getScoreLine();
                }
            }
        } catch (Exception e) {
            log.error("获取考试特控线失败：examId={}, examType={}", examId, examType, e);
        }
        
        // 如果没有配置特控线，使用默认值（根据考试类型）
        if ("历史类".equals(examType)) {
            return BigDecimal.valueOf(520);
        } else {
            return BigDecimal.valueOf(518);
        }
    }
    
    /**
     * 获取省控线分数（物理类）
     */
    private BigDecimal getProvinceControlLineScore() {
        // 安徽省2025年物理类特控线（官方数据）
        return BigDecimal.valueOf(514);
    }
    
    /**
     * 根据考试类型获取省控线分数
     */
    private BigDecimal getProvinceControlLineScore(String examType) {
        if ("历史类".equals(examType)) {
            return BigDecimal.valueOf(515); // 安徽省2025年历史类特控线
        } else {
            return BigDecimal.valueOf(514); // 安徽省2025年物理类特控线
        }
    }
    
    /**
     * 获取全考试临界学生分析
     */
    private TeacherDashboardRespVO.CriticalStudentAnalysis getGlobalCriticalStudentAnalysis(Long examId, Integer range) {
        // 获取全考试范围内的临界学生
        TeacherDashboardRespVO.CriticalStudentAnalysis analysis = new TeacherDashboardRespVO.CriticalStudentAnalysis();
        
        // 使用全考试数据查询临界学生
        List<ExamScoreDO> allScores = examScoreMapper.selectList(new LambdaQueryWrapperX<ExamScoreDO>()
                .eq(ExamScoreDO::getExamId, examId)
                .orderByDesc(ExamScoreDO::getTotalScore));
        
        List<TeacherDashboardRespVO.CriticalStudentInfo> critical985Students = new ArrayList<>();
        List<TeacherDashboardRespVO.CriticalStudentInfo> critical211Students = new ArrayList<>();
        List<TeacherDashboardRespVO.CriticalStudentInfo> criticalFirstTierStudents = new ArrayList<>();
        List<TeacherDashboardRespVO.CriticalStudentInfo> criticalSecondTierStudents = new ArrayList<>();
        
        for (ExamScoreDO score : allScores) {
            if (score.getTotalScore() != null) {
                BigDecimal totalScore = score.getTotalScore();
                
                // 985临界线（680分）
                if (totalScore.compareTo(BigDecimal.valueOf(680 - range)) >= 0 && 
                    totalScore.compareTo(BigDecimal.valueOf(680 + range)) <= 0) {
                    critical985Students.add(createCriticalStudentInfo(score, "985", BigDecimal.valueOf(680)));
                }
                // 211临界线（650分）
                else if (totalScore.compareTo(BigDecimal.valueOf(650 - range)) >= 0 && 
                         totalScore.compareTo(BigDecimal.valueOf(650 + range)) <= 0) {
                    critical211Students.add(createCriticalStudentInfo(score, "211", BigDecimal.valueOf(650)));
                }
                // 一本临界线（620分）
                else if (totalScore.compareTo(BigDecimal.valueOf(620 - range)) >= 0 && 
                         totalScore.compareTo(BigDecimal.valueOf(620 + range)) <= 0) {
                    criticalFirstTierStudents.add(createCriticalStudentInfo(score, "一本", BigDecimal.valueOf(620)));
                }
                // 二本临界线（550分）
                else if (totalScore.compareTo(BigDecimal.valueOf(550 - range)) >= 0 && 
                         totalScore.compareTo(BigDecimal.valueOf(550 + range)) <= 0) {
                    criticalSecondTierStudents.add(createCriticalStudentInfo(score, "二本", BigDecimal.valueOf(550)));
                }
            }
        }
        
        analysis.setCritical985Students(critical985Students);
        analysis.setCritical211Students(critical211Students);
        analysis.setCriticalFirstTierStudents(criticalFirstTierStudents);
        analysis.setCriticalSecondTierStudents(criticalSecondTierStudents);
        
        return analysis;
    }
    
    /**
     * 创建临界学生信息
     */
    private TeacherDashboardRespVO.CriticalStudentInfo createCriticalStudentInfo(ExamScoreDO score, String targetLevel, BigDecimal targetScore) {
        TeacherDashboardRespVO.CriticalStudentInfo student = new TeacherDashboardRespVO.CriticalStudentInfo();
        student.setStudentId(score.getStudentId());
        student.setStudentName(score.getStudentName());
        student.setStudentNo(score.getStudentNo());
        student.setCurrentScore(score.getTotalScore());
        student.setTargetScore(targetScore);
        student.setTargetLevel(targetLevel);
        
        if (score.getTotalScore() != null) {
            student.setScoreDiff(targetScore.subtract(score.getTotalScore()));
        }
        
        student.setImprovementSuggestion("加强薄弱科目，重点突破" + targetLevel + "分数线");
        
        return student;
    }
    
    /**
     * 获取全考试升学趋势分析
     */
    private TeacherDashboardRespVO.AdmissionTrendAnalysis getGlobalAdmissionTrendAnalysis(Long examId, Integer limit) {
        // 全考试视图下的趋势分析，使用年级整体数据
        TeacherDashboardRespVO.AdmissionTrendAnalysis analysis = new TeacherDashboardRespVO.AdmissionTrendAnalysis();
        
        // 简化实现：返回基本的趋势信息
        analysis.setOverallTrend("稳定");
        analysis.setChangeRate(BigDecimal.valueOf(2.5));
        
        // 创建默认的趋势点
        List<TeacherDashboardRespVO.AdmissionTrendPoint> trendPoints = new ArrayList<>();
        TeacherDashboardRespVO.AdmissionTrendPoint point = new TeacherDashboardRespVO.AdmissionTrendPoint();
        point.setExamName("当前考试");
        point.setExamDate(LocalDateTime.now());
        point.setFirstTierRate(BigDecimal.valueOf(40.0));
        point.setRate985(BigDecimal.valueOf(5.0));
        point.setRate211(BigDecimal.valueOf(15.0));
        point.setClassAvgScore(BigDecimal.valueOf(580.0));
        trendPoints.add(point);
        
        analysis.setTrendPoints(trendPoints);
        
        return analysis;
    }
    
    /**
     * 获取全考试班级信息（汇总信息）
     */
    private TeacherDashboardRespVO.ClassBasicInfo getGlobalClassInfo(Long examId) {
        ExamTestDO examTest = examTestMapper.selectById(examId);
        if (examTest == null) {
            return null;
        }
        
        TeacherDashboardRespVO.ClassBasicInfo classInfo = new TeacherDashboardRespVO.ClassBasicInfo();
        
        // 获取全考试统计信息
        Map<String, Object> globalStats = examScoreMapper.selectGradeStatistics(examId);
        if (globalStats != null) {
            Object totalStudentsObj = globalStats.get("totalStudents");
            if (totalStudentsObj != null) {
                classInfo.setTotalStudents(((Number) totalStudentsObj).intValue());
            }
        }
        
        // 设置全考试视图的基本信息
        classInfo.setClassId(0L); // 全考试视图使用0作为标识
        classInfo.setClassName("全考试统计");
        classInfo.setGrade("全年级");
        classInfo.setTeacherName("校领导");
        classInfo.setClassType("全考试视图");
        classInfo.setClassTarget("整体提升，全面发展");
        
        return classInfo;
    }
    
    /**
     * 创建全考试默认班级信息
     */
    private TeacherDashboardRespVO.ClassBasicInfo createGlobalDefaultClassInfo(Long examId) {
        TeacherDashboardRespVO.ClassBasicInfo classInfo = new TeacherDashboardRespVO.ClassBasicInfo();
        
        classInfo.setClassId(0L);
        classInfo.setClassName("全考试统计");
        classInfo.setGrade("全年级");
        classInfo.setTotalStudents(0);
        classInfo.setTeacherName("校领导");
        classInfo.setClassType("全考试视图");
        classInfo.setClassTarget("整体提升，全面发展");
        
        return classInfo;
    }

    @Override
    public TeacherDashboardRespVO.ClassBasicInfo getClassOverview(@Valid ClassOverviewReqVO reqVO) {
        return getClassBasicInfo(reqVO.getClassId());
    }

    @Override
    public AdmissionAnalysisRespVO getAdmissionAnalysis(@Valid AdmissionAnalysisReqVO reqVO) {
        log.info("获取升学分析数据，班级ID: {}, 考试ID: {}", reqVO.getClassId(), reqVO.getExamId());
        
        AdmissionAnalysisRespVO respVO = new AdmissionAnalysisRespVO();
        
        // 获取班级基本信息
        AdmissionAnalysisRespVO.ClassBasicInfo classInfo = new AdmissionAnalysisRespVO.ClassBasicInfo();
        ExamClassDO examClass = examClassMapper.selectById(reqVO.getClassId());
        ExamTestDO examTest = examTestMapper.selectById(reqVO.getExamId());
        
        if (examClass != null) {
            classInfo.setClassId(examClass.getId());
            classInfo.setClassName(examClass.getClassName());
            classInfo.setTotalStudents(examClass.getStudentCount());
        }
        
        if (examTest != null) {
            classInfo.setExamName(examTest.getExamName());
            classInfo.setExamDate(examTest.getExamDate());
        }
        
        respVO.setClassInfo(classInfo);

        // 获取升学预测统计
        respVO.setPredictionStats(convertToAdmissionPredictionStats(reqVO.getClassId(), reqVO.getExamId()));

        // 获取临界学生分析
        if (Boolean.TRUE.equals(reqVO.getIncludeCriticalStudents())) {
            respVO.setCriticalStudents(getCriticalStudentAnalysisForAdmission(reqVO.getClassId(), reqVO.getExamId(), reqVO.getCriticalScoreRange()));
        }

        // 获取目标达成情况
        if (Boolean.TRUE.equals(reqVO.getIncludeTargetAnalysis())) {
            respVO.setTargetAchievement(getTargetAchievementInfoForAdmission(reqVO.getClassId(), reqVO.getExamId()));
        }

        // 获取升学趋势分析
        if (Boolean.TRUE.equals(reqVO.getIncludeTrendAnalysis())) {
            respVO.setTrendAnalysis(getAdmissionTrendAnalysisForAdmission(reqVO.getClassId(), 5));
        }

        // 获取学生详细升学信息
        respVO.setStudentDetails(getStudentAdmissionDetails(reqVO.getClassId(), reqVO.getExamId()));

        return respVO;
    }

    @Override
    public TeacherDashboardRespVO.ScoreStatistics getClassScoreStatistics(Long classId, Long examId) {
        TeacherDashboardRespVO.ScoreStatistics statistics = new TeacherDashboardRespVO.ScoreStatistics();
        
        // 获取总分统计
        Map<String, Object> totalStats = examScoreMapper.selectClassScoreStatistics(classId, examId);
        if (totalStats != null) {
            TeacherDashboardRespVO.TotalScoreStats totalScoreStats = new TeacherDashboardRespVO.TotalScoreStats();
            totalScoreStats.setAvgScore(getBigDecimalFromMap(totalStats, "avgScore"));
            totalScoreStats.setMaxScore(getBigDecimalFromMap(totalStats, "maxScore"));
            totalScoreStats.setMinScore(getBigDecimalFromMap(totalStats, "minScore"));
            totalScoreStats.setStandardDeviation(getBigDecimalFromMap(totalStats, "standardDeviation"));
            
            // 获取年级平均分并计算差值
            Map<String, Object> gradeStats = examScoreMapper.selectGradeStatistics(examId);
            if (gradeStats != null && gradeStats.get("avgScore") != null) {
                BigDecimal gradeAvg = getBigDecimalFromMap(gradeStats, "avgScore");
                if (totalScoreStats.getAvgScore() != null && gradeAvg != null) {
                    totalScoreStats.setGradeAvgDiff(totalScoreStats.getAvgScore().subtract(gradeAvg));
                }
            }
            
            // 获取班级在年级中的排名
            Integer gradeRank = getClassRankInGrade(classId, examId);
            totalScoreStats.setGradeRank(gradeRank);
            
            statistics.setTotalScore(totalScoreStats);
        }

        // 获取各科成绩统计
        List<Map<String, Object>> subjectStats = examScoreMapper.selectClassSubjectStatistics(classId, examId);
        Map<String, TeacherDashboardRespVO.SubjectScoreStats> subjectScores = new HashMap<>();
        
        for (Map<String, Object> subjectStat : subjectStats) {
            TeacherDashboardRespVO.SubjectScoreStats subjectScoreStats = new TeacherDashboardRespVO.SubjectScoreStats();
            subjectScoreStats.setSubjectName((String) subjectStat.get("subjectName"));
            subjectScoreStats.setAvgScore(getBigDecimalFromMap(subjectStat, "avgScore"));
            subjectScoreStats.setMaxScore(getBigDecimalFromMap(subjectStat, "maxScore"));
            subjectScoreStats.setMinScore(getBigDecimalFromMap(subjectStat, "minScore"));
            subjectScoreStats.setPassRate(getBigDecimalFromMap(subjectStat, "passRate"));
            subjectScoreStats.setExcellentRate(getBigDecimalFromMap(subjectStat, "excellentRate"));
            
            // 设置满分（根据科目）
            String subjectName = subjectScoreStats.getSubjectName();
            if ("语文".equals(subjectName) || "数学".equals(subjectName) || "英语".equals(subjectName)) {
                subjectScoreStats.setFullScore(BigDecimal.valueOf(150));
            } else {
                subjectScoreStats.setFullScore(BigDecimal.valueOf(100));
            }
            
            subjectScores.put(subjectName, subjectScoreStats);
        }
        statistics.setSubjectScores(subjectScores);

        // 获取分数段分布
        List<Map<String, Object>> distributionData = examScoreMapper.selectClassScoreDistribution(classId, examId);
        List<TeacherDashboardRespVO.ScoreRangeDistribution> scoreDistribution = new ArrayList<>();
        
        for (Map<String, Object> data : distributionData) {
            TeacherDashboardRespVO.ScoreRangeDistribution distribution = new TeacherDashboardRespVO.ScoreRangeDistribution();
            distribution.setScoreRange((String) data.get("scoreRange"));
            distribution.setCount(((Number) data.get("count")).intValue());
            distribution.setPercentage(getBigDecimalFromMap(data, "percentage"));
            
            // 设置等级
            String scoreRange = distribution.getScoreRange();
            if (scoreRange.contains("650以上")) {
                distribution.setLevel("优秀");
            } else if (scoreRange.contains("600-649")) {
                distribution.setLevel("良好");
            } else if (scoreRange.contains("550-599")) {
                distribution.setLevel("中等");
            } else if (scoreRange.contains("500-549")) {
                distribution.setLevel("及格");
            } else {
                distribution.setLevel("不及格");
            }
            
            scoreDistribution.add(distribution);
        }
        statistics.setScoreDistribution(scoreDistribution);

        // 计算及格率统计
        TeacherDashboardRespVO.PassRateStats passRateStats = calculatePassRateStats(scoreDistribution, subjectScores);
        statistics.setPassRate(passRateStats);

        return statistics;
    }

    @Override
    public TeacherDashboardRespVO.AdmissionPredictionStats getAdmissionPredictionStats(Long classId, Long examId) {
        // 获取班级所有学生成绩
        List<ExamScoreDO> classScores = examScoreMapper.selectList(new LambdaQueryWrapperX<ExamScoreDO>()
                .eq(ExamScoreDO::getExamId, examId)
                .eq(ExamScoreDO::getClassId, classId)
                .orderByDesc(ExamScoreDO::getTotalScore));
        
        if (classScores.isEmpty()) {
            return new TeacherDashboardRespVO.AdmissionPredictionStats();
        }
        
        // 获取全考试学生总数用于计算等效位次
        List<ExamScoreDO> allScores = examScoreMapper.selectList(new LambdaQueryWrapperX<ExamScoreDO>()
                .eq(ExamScoreDO::getExamId, examId)
                .orderByDesc(ExamScoreDO::getTotalScore));
        
        int totalStudents = allScores.size();
        
        TeacherDashboardRespVO.AdmissionPredictionStats stats = new TeacherDashboardRespVO.AdmissionPredictionStats();
        
        // 分类统计学生
        List<TeacherDashboardRespVO.AdmissionStudentInfo> predicted985Students = new ArrayList<>();
        List<TeacherDashboardRespVO.AdmissionStudentInfo> predicted211Students = new ArrayList<>();
        List<TeacherDashboardRespVO.AdmissionStudentInfo> predictedDoubleFirstClassStudents = new ArrayList<>();
        List<TeacherDashboardRespVO.AdmissionStudentInfo> predictedSpecialControlStudents = new ArrayList<>();
        List<TeacherDashboardRespVO.AdmissionStudentInfo> predictedUndergraduateStudents = new ArrayList<>();
        List<TeacherDashboardRespVO.AdmissionStudentInfo> predictedSpecialtyStudents = new ArrayList<>();
        List<TeacherDashboardRespVO.AdmissionStudentInfo> belowLineStudents = new ArrayList<>();
        
        // 计算等效位次并分类学生
        for (ExamScoreDO score : classScores) {
            if (score.getTotalScore() == null) continue;
            
            // 确定学生的考试类型
            String examType = determineExamType(score);
            
            // 根据考试类型获取对应的特控线和省控线
            BigDecimal controlLineScore = getExamControlLineScore(examId, examType);
            BigDecimal provinceControlLineScore = getProvinceControlLineScore(examType);
            
            // 计算2025等效位次（基于特控线和省控线）
            int equivalentRanking2025 = calculateEquivalentRanking2025(score, controlLineScore, provinceControlLineScore);
            
            TeacherDashboardRespVO.AdmissionStudentInfo studentInfo = createAdmissionStudentInfo(score, equivalentRanking2025);
            
            // 计算等效分用于分类判断
            BigDecimal equivalentScore = score.getTotalScore().subtract(controlLineScore).add(provinceControlLineScore);
            
            // 获取动态分数线配置
            Map<String, Integer> scoreLineConfig = getScoreLineConfig(examType);
            int score985 = scoreLineConfig.get("score985");
            int score211 = scoreLineConfig.get("score211");
            int scoreDoubleFirst = scoreLineConfig.get("scoreDoubleFirst");
            int scoreSpecialControl = scoreLineConfig.get("scoreSpecialControl");
            int scoreUndergraduate = scoreLineConfig.get("scoreUndergraduate");
            int scoreSpecialist = scoreLineConfig.get("scoreSpecialist");
            
            // 根据等效分进行分数线分类学生
            if (equivalentScore.compareTo(BigDecimal.valueOf(score985)) >= 0) {
                predicted985Students.add(studentInfo);
                predicted211Students.add(studentInfo);
                predictedDoubleFirstClassStudents.add(studentInfo);
                predictedSpecialControlStudents.add(studentInfo);
                predictedUndergraduateStudents.add(studentInfo);
                predictedSpecialtyStudents.add(studentInfo);
            } else if (equivalentScore.compareTo(BigDecimal.valueOf(score211)) >= 0) {
                predicted211Students.add(studentInfo);
                predictedDoubleFirstClassStudents.add(studentInfo);
                predictedSpecialControlStudents.add(studentInfo);
                predictedUndergraduateStudents.add(studentInfo);
                predictedSpecialtyStudents.add(studentInfo);
            } else if (equivalentScore.compareTo(BigDecimal.valueOf(scoreDoubleFirst)) >= 0) {
                predictedDoubleFirstClassStudents.add(studentInfo);
                predictedSpecialControlStudents.add(studentInfo);
                predictedUndergraduateStudents.add(studentInfo);
                predictedSpecialtyStudents.add(studentInfo);
            } else if (equivalentScore.compareTo(BigDecimal.valueOf(scoreSpecialControl)) >= 0) {
                predictedSpecialControlStudents.add(studentInfo);
                predictedUndergraduateStudents.add(studentInfo);
                predictedSpecialtyStudents.add(studentInfo);
            } else if (equivalentScore.compareTo(BigDecimal.valueOf(scoreUndergraduate)) >= 0) {
                predictedUndergraduateStudents.add(studentInfo);
                predictedSpecialtyStudents.add(studentInfo);
            } else if (equivalentScore.compareTo(BigDecimal.valueOf(scoreSpecialist)) >= 0) {
                predictedSpecialtyStudents.add(studentInfo);
            } else {
                belowLineStudents.add(studentInfo);
            }
        }
        
        int classStudentCount = classScores.size();
        
        // 设置统计数据
        stats.setPredicted985Count(predicted985Students.size());
        stats.setPredicted985Rate(calculateRate(predicted985Students.size(), classStudentCount));
        stats.setPredicted985Students(predicted985Students);
        
        stats.setPredicted211Count(predicted211Students.size());
        stats.setPredicted211Rate(calculateRate(predicted211Students.size(), classStudentCount));
        stats.setPredicted211Students(predicted211Students);
        
        stats.setPredictedDoubleFirstClassCount(predictedDoubleFirstClassStudents.size());
        stats.setPredictedDoubleFirstClassRate(calculateRate(predictedDoubleFirstClassStudents.size(), classStudentCount));
        stats.setPredictedDoubleFirstClassStudents(predictedDoubleFirstClassStudents);
        
        stats.setPredictedSpecialControlCount(predictedSpecialControlStudents.size());
        stats.setPredictedSpecialControlRate(calculateRate(predictedSpecialControlStudents.size(), classStudentCount));
        stats.setPredictedSpecialControlStudents(predictedSpecialControlStudents);
        
        stats.setPredictedUndergraduateCount(predictedUndergraduateStudents.size());
        stats.setPredictedUndergraduateRate(calculateRate(predictedUndergraduateStudents.size(), classStudentCount));
        stats.setPredictedUndergraduateStudents(predictedUndergraduateStudents);
        
        stats.setPredictedSpecialtyCount(predictedSpecialtyStudents.size());
        stats.setPredictedSpecialtyRate(calculateRate(predictedSpecialtyStudents.size(), classStudentCount));
        stats.setPredictedSpecialtyStudents(predictedSpecialtyStudents);
        
        stats.setBelowLineCount(belowLineStudents.size());
        stats.setBelowLineRate(calculateRate(belowLineStudents.size(), classStudentCount));
        stats.setBelowLineStudents(belowLineStudents);
        
        // 设置兼容性字段
        stats.setPredictedFirstTierCount(predictedSpecialControlStudents.size());
        stats.setPredictedFirstTierRate(stats.getPredictedSpecialControlRate());
        stats.setPredictedSecondTierCount(predictedUndergraduateStudents.size());
        stats.setPredictedSecondTierRate(stats.getPredictedUndergraduateRate());
        
        return stats;
    }

    // ==================== 私有辅助方法 ====================

    /**
     * 验证教师看板请求参数
     */
    private void validateTeacherDashboardRequest(TeacherDashboardReqVO reqVO) {
        // 检查用户是否具有校领导角色
        boolean isSchoolAdmin = permissionService.hasAnyRoles(reqVO.getTeacherId(), "school_admin");
        
        // 验证教师和班级的关联关系
        if (reqVO.getClassId() != null) {
            ExamClassDO examClass = examClassMapper.selectById(reqVO.getClassId());
            if (examClass == null) {
                log.warn("班级不存在，班级ID: {}", reqVO.getClassId());
                throw new IllegalArgumentException("班级不存在");
            }

            if (isSchoolAdmin) {
                log.info("校领导用户访问班级数据，教师ID: {}, 班级ID: {}", reqVO.getTeacherId(), reqVO.getClassId());
                // 校领导可以访问任何班级的数据，跳过教师与班级匹配检查
            } else if (!reqVO.getTeacherId().equals(examClass.getTeacherId())) {
                log.warn("教师与班级不匹配，教师ID: {}, 班级ID: {}, 班级教师ID: {}",
                    reqVO.getTeacherId(), reqVO.getClassId(), examClass.getTeacherId());
                throw new IllegalArgumentException("教师与班级不匹配");
            }
        } else {
            // 如果没有传递班级ID，只有校领导可以访问全考试数据
            if (!isSchoolAdmin) {
                log.warn("普通教师必须指定班级ID，教师ID: {}", reqVO.getTeacherId());
                throw new IllegalArgumentException("普通教师必须指定班级ID");
            }
            log.info("校领导用户访问全考试数据，教师ID: {}, 考试ID: {}", reqVO.getTeacherId(), reqVO.getExamId());
        }

        // 验证考试和班级的关联关系
        if (reqVO.getExamId() != null && reqVO.getClassId() != null) {
            ExamTestDO examTest = examTestMapper.selectById(reqVO.getExamId());
            if (examTest == null) {
                log.warn("考试不存在，考试ID: {}", reqVO.getExamId());
                throw new IllegalArgumentException("考试不存在");
            }

            // 添加详细的调试日志
            log.info("验证考试和班级关联关系 - 考试ID: {}, 班级ID: {}, 考试班级IDs: {}, 班级IDs类型: {}", 
                reqVO.getExamId(), reqVO.getClassId(), examTest.getClassIds(), 
                examTest.getClassIds() != null ? examTest.getClassIds().getClass().getName() : "null");
            
            if (examTest.getClassIds() != null && !examTest.getClassIds().isEmpty()) {
                // 打印每个classId的详细信息
                for (int i = 0; i < examTest.getClassIds().size(); i++) {
                    Long classId = examTest.getClassIds().get(i);
                    log.info("班级ID[{}]: 值={}, 类型={}, 与传入classId({})比较结果: {}", 
                        i, classId, classId != null ? classId.getClass().getName() : "null", 
                        reqVO.getClassId(), Objects.equals(classId, reqVO.getClassId()));
                }
            }

            // 兼容新旧数据格式：优先使用classIds，如果为空则检查是否有classId字段匹配
            boolean isClassMatched = false;
            if (examTest.getClassIds() != null && !examTest.getClassIds().isEmpty()) {
                // 新格式：使用classIds数组
                // 确保传递的classId（如1）能与数据库中的[1,2,3]匹配
                isClassMatched = examTest.getClassIds().contains(reqVO.getClassId());
                log.info("使用classIds数组匹配结果: {}", isClassMatched);
                
                // 如果contains方法失败，尝试手动遍历比较
                if (!isClassMatched) {
                    for (Long classId : examTest.getClassIds()) {
                        if (Objects.equals(classId, reqVO.getClassId())) {
                            isClassMatched = true;
                            log.info("手动遍历匹配成功: classId={}, reqVO.getClassId()={}", classId, reqVO.getClassId());
                            break;
                        }
                    }
                }
            } else {
                // 旧格式兼容：通过数据库查询检查class_id字段
                // 如果classIds为空，可能是数据库还没有执行迁移脚本，或者数据为空
                log.warn("考试classIds字段为空，尝试使用JSON_CONTAINS查询数据库验证");
                
                // 方法1：使用JSON_CONTAINS查询（适用于已有class_ids字段的情况）
                LambdaQueryWrapperX<ExamTestDO> jsonWrapper = new LambdaQueryWrapperX<>();
                jsonWrapper.eq(ExamTestDO::getId, reqVO.getExamId())
                          .apply("JSON_CONTAINS(class_ids, {0})", String.valueOf(reqVO.getClassId()))
                          .eq(ExamTestDO::getDeleted, false);
                List<ExamTestDO> jsonResults = examTestMapper.selectList(jsonWrapper);
                
                if (!jsonResults.isEmpty()) {
                    isClassMatched = true;
                    log.info("使用JSON_CONTAINS查询匹配成功");
                } else {
                    // 方法2：使用原始class_id字段查询（适用于未迁移的情况）
                    LambdaQueryWrapperX<ExamTestDO> classIdWrapper = new LambdaQueryWrapperX<>();
                    classIdWrapper.eq(ExamTestDO::getId, reqVO.getExamId())
                                 .apply("class_id = {0}", reqVO.getClassId())
                                 .eq(ExamTestDO::getDeleted, false);
                    List<ExamTestDO> classIdResults = examTestMapper.selectList(classIdWrapper);
                    isClassMatched = !classIdResults.isEmpty();
                    log.info("使用旧格式class_id字段匹配结果: {}", isClassMatched);
                }
            }

            if (!isClassMatched) {
                log.warn("考试与班级不匹配，考试ID: {}, 班级ID: {}, 考试班级IDs: {}",
                    reqVO.getExamId(), reqVO.getClassId(), examTest.getClassIds());
                throw new IllegalArgumentException("考试与班级不匹配");
            }
        }
    }

    /**
     * 获取班级基本信息
     */
    private TeacherDashboardRespVO.ClassBasicInfo getClassBasicInfo(Long classId) {
        ExamClassDO examClass = examClassMapper.selectById(classId);
        if (examClass == null) {
            return null;
        }

        TeacherDashboardRespVO.ClassBasicInfo classInfo = new TeacherDashboardRespVO.ClassBasicInfo();
        classInfo.setClassId(examClass.getId());
        classInfo.setClassName(examClass.getClassName());
        classInfo.setGrade(examClass.getGrade());
        classInfo.setTotalStudents(examClass.getStudentCount());
        // 这里可以根据teacherId查询教师姓名，暂时设置默认值
        classInfo.setTeacherName("班主任");
        // 根据年级和班级名称推断班级类型，暂时设置默认值
        classInfo.setClassType("普通班");
        // 这里可以根据实际需求设置班级目标
        classInfo.setClassTarget("一本上线率80%");

        return classInfo;
    }

    /**
     * 获取最新考试概况
     */
    private TeacherDashboardRespVO.LatestExamOverview getLatestExamOverview(Long classId, Long examId) {
        ExamTestDO examTest = examTestMapper.selectById(examId);
        if (examTest == null) {
            return null;
        }

        TeacherDashboardRespVO.LatestExamOverview overview = new TeacherDashboardRespVO.LatestExamOverview();
        overview.setExamId(examTest.getId());
        overview.setExamName(examTest.getExamName());
        overview.setExamDate(examTest.getExamDate());

        // 获取班级统计信息
        Map<String, Object> classStats = examScoreMapper.selectClassScoreStatistics(classId, examId);
        if (classStats != null) {
            overview.setClassAvgScore(getBigDecimalFromMap(classStats, "avgScore"));
            overview.setClassMaxScore(getBigDecimalFromMap(classStats, "maxScore"));
            overview.setClassMinScore(getBigDecimalFromMap(classStats, "minScore"));
            
            // 参考人数 = 总人数（这里简化处理）
            Object totalCountObj = classStats.get("totalCount");
            if (totalCountObj != null && totalCountObj instanceof Number) {
                int totalCount = ((Number) totalCountObj).intValue();
                overview.setParticipantCount(totalCount);
                overview.setAbsentCount(0); // 简化处理，实际应该计算缺考人数
            }
        }

        // 获取年级平均分
        Map<String, Object> gradeStats = examScoreMapper.selectGradeStatistics(examId);
        if (gradeStats != null) {
            overview.setGradeAvgScore(getBigDecimalFromMap(gradeStats, "avgScore"));
        }

        // 获取班级在年级中的排名
        Integer classRank = getClassRankInGrade(classId, examId);
        overview.setClassRankInGrade(classRank);
        
        Integer totalClasses = examScoreMapper.selectTotalClassesInGrade(classId, examId);
        overview.setTotalClassesInGrade(totalClasses);

        return overview;
    }

    /**
     * 从Map中安全获取BigDecimal值
     */
    private BigDecimal getBigDecimalFromMap(Map<String, Object> map, String key) {
        Object value = map.get(key);
        if (value == null) {
            return null;
        }
        if (value instanceof BigDecimal) {
            return (BigDecimal) value;
        }
        if (value instanceof Number) {
            return BigDecimal.valueOf(((Number) value).doubleValue());
        }
        return null;
    }

    /**
     * 从Map中安全获取Integer值
     */
    private Integer getIntegerFromMap(Map<String, Object> map, String key) {
        Object value = map.get(key);
        if (value == null) {
            return null;
        }
        if (value instanceof Integer) {
            return (Integer) value;
        }
        if (value instanceof Number) {
            return ((Number) value).intValue();
        }
        return null;
    }

    /**
     * 计算及格率统计
     */
    private TeacherDashboardRespVO.PassRateStats calculatePassRateStats(
            List<TeacherDashboardRespVO.ScoreRangeDistribution> scoreDistribution,
            Map<String, TeacherDashboardRespVO.SubjectScoreStats> subjectScores) {

        TeacherDashboardRespVO.PassRateStats passRateStats = new TeacherDashboardRespVO.PassRateStats();

        // 计算总体统计
        int totalStudents = scoreDistribution.stream().mapToInt(TeacherDashboardRespVO.ScoreRangeDistribution::getCount).sum();
        int excellentCount = 0;
        int goodCount = 0;
        int passCount = 0;
        int failCount = 0;

        for (TeacherDashboardRespVO.ScoreRangeDistribution distribution : scoreDistribution) {
            String level = distribution.getLevel();
            int count = distribution.getCount();

            switch (level) {
                case "优秀":
                    excellentCount += count;
                    break;
                case "良好":
                    goodCount += count;
                    break;
                case "中等":
                case "及格":
                    passCount += count;
                    break;
                case "不及格":
                    failCount += count;
                    break;
            }
        }

        if (totalStudents > 0) {
            passRateStats.setExcellentRate(BigDecimal.valueOf(100.0 * excellentCount / totalStudents).setScale(1, RoundingMode.HALF_UP));
            passRateStats.setGoodRate(BigDecimal.valueOf(100.0 * goodCount / totalStudents).setScale(1, RoundingMode.HALF_UP));
            passRateStats.setOverallPassRate(BigDecimal.valueOf(100.0 * (totalStudents - failCount) / totalStudents).setScale(1, RoundingMode.HALF_UP));
            passRateStats.setFailRate(BigDecimal.valueOf(100.0 * failCount / totalStudents).setScale(1, RoundingMode.HALF_UP));
        }

        // 设置各科及格率
        Map<String, BigDecimal> subjectPassRates = new HashMap<>();
        for (Map.Entry<String, TeacherDashboardRespVO.SubjectScoreStats> entry : subjectScores.entrySet()) {
            subjectPassRates.put(entry.getKey(), entry.getValue().getPassRate());
        }
        passRateStats.setSubjectPassRates(subjectPassRates);

        return passRateStats;
    }

    // ==================== 其他接口方法的实现 ====================

    @Override
    public List<TeacherDashboardRespVO.TopStudentInfo> getTopStudents(Long classId, Long examId, Integer topN) {
        List<Map<String, Object>> topStudentsData;
        
        if (topN == null) {
            // 如果topN为null，返回所有排名数据
            // 获取科目类型（默认使用物理类）
            String subjectType = "物理类";
            try {
                // 尝试从考试数据中获取科目类型
                ExamScoreDO sampleScore = examScoreMapper.selectOne(new LambdaQueryWrapperX<ExamScoreDO>()
                    .eq(ExamScoreDO::getExamId, examId)
                    .last("LIMIT 1"));
                if (sampleScore != null) {
                    subjectType = determineExamType(sampleScore);
                }
            } catch (Exception e) {
                log.warn("获取科目类型失败，使用默认值: {}", e.getMessage());
            }
            
            // 获取分数线配置
            Map<String, Integer> scoreLines = getScoreLineConfig(subjectType);
            topStudentsData = examScoreMapper.selectClassAllStudents(classId, examId, 
                scoreLines.get("score985"), scoreLines.get("score211"), 
                scoreLines.get("scoreFirstTier"), scoreLines.get("scoreSecondTier"));
        } else {
            if (topN <= 0) {
                topN = 10;
            }
            topStudentsData = examScoreMapper.selectClassTopStudents(classId, examId, topN);
        }
        
        List<TeacherDashboardRespVO.TopStudentInfo> topStudents = new ArrayList<>();

        for (Map<String, Object> data : topStudentsData) {
            TeacherDashboardRespVO.TopStudentInfo student = new TeacherDashboardRespVO.TopStudentInfo();
            student.setStudentId(((Number) data.get("student_id")).longValue());
            student.setStudentName((String) data.get("student_name"));
            student.setStudentNo((String) data.get("student_no"));
            student.setClassName((String) data.get("class_name"));
            student.setTotalScore(getBigDecimalFromMap(data, "total_score"));
            student.setClassRank(getIntegerFromMap(data, "class_rank"));
            student.setGradeRank(getIntegerFromMap(data, "grade_rank"));
            student.setPredictedAdmissionLevel((String) data.get("predictedAdmissionLevel"));

            // 根据预测层次设置目标院校（示例）
            String level = student.getPredictedAdmissionLevel();
            if ("985".equals(level)) {
                student.setTargetUniversity("清华大学/北京大学");
            } else if ("211".equals(level)) {
                student.setTargetUniversity("中山大学/华南理工大学");
            } else if ("一本".equals(level)) {
                student.setTargetUniversity("深圳大学/广东工业大学");
            }
            
            // 设置新增字段
            student.setSubjectCombination((String) data.get("subject_combination"));
            student.setFirstSubject((String) data.get("first_subject"));
            student.setSecondSubject((String) data.get("second_subject"));
            student.setExamType((String) data.get("exam_type"));
            student.setTotalScoreAssigned(getBigDecimalFromMap(data, "total_score_assigned"));
            student.setCombinationRank(getIntegerFromMap(data, "combination_rank"));
            student.setSchoolRank(getIntegerFromMap(data, "school_rank"));
            student.setTotalUnionRank(getIntegerFromMap(data, "total_union_rank"));

            // 计算等效分和等效位次
            try {
                // 获取学生的考试类型
                String examType = (String) data.get("exam_type");
                if (examType == null || examType.isEmpty()) {
                    // 如果没有考试类型，尝试从学生数据推断
                    examType = "物理类"; // 默认值
                }
                
                // 根据考试类型获取对应的控制线分数和省控线分数
                BigDecimal controlLineScore = getExamControlLineScore(examId, examType);
                BigDecimal provinceControlLineScore = getProvinceControlLineScore(examType);
                
                // 优先使用赋分字段total_score_assigned，如果没有则使用原始分total_score
                BigDecimal scoreForCalculation = student.getTotalScoreAssigned() != null ? 
                    student.getTotalScoreAssigned() : student.getTotalScore();
                
                if (scoreForCalculation != null && controlLineScore != null && provinceControlLineScore != null) {
                    // 计算等效分：原始分数 - 特控线分数 + 省控线分数
                    BigDecimal equivalentScore = equivalentScoreRankService.calculateEquivalentScore(
                            scoreForCalculation, controlLineScore, provinceControlLineScore);
                    student.setEquivalentScore(equivalentScore);
                    
                    // 计算等效位次
                    Integer equivalentRank = equivalentScoreRankService.calculateEquivalentRank(
                            equivalentScore, "安徽", 2025, examType);
                    student.setEquivalentRank(equivalentRank);
                } else {
                    log.warn("无法计算等效分和等效位次：学生ID={}, 考试类型={}, 赋分={}, 原始分={}, 控制线分数={}, 省控线分数={}", 
                            student.getStudentId(), examType, student.getTotalScoreAssigned(), student.getTotalScore(), controlLineScore, provinceControlLineScore);
                }
            } catch (Exception e) {
                log.error("计算等效分和等效位次失败：学生ID={}", student.getStudentId(), e);
                // 计算失败时设置为null，不影响其他数据的返回
                student.setEquivalentScore(null);
                student.setEquivalentRank(null);
            }

            topStudents.add(student);
        }

        return topStudents;
    }

    @Override
    public List<TeacherDashboardRespVO.ProgressStudentInfo> getMostImprovedStudents(Long classId, Long currentExamId, Long previousExamId, Integer limit) {
        if (limit == null || limit <= 0) {
            limit = 10;
        }

        List<Map<String, Object>> improvedData = examScoreMapper.selectMostImprovedStudents(classId, currentExamId, previousExamId, limit);
        List<TeacherDashboardRespVO.ProgressStudentInfo> improvedStudents = new ArrayList<>();

        for (Map<String, Object> data : improvedData) {
            TeacherDashboardRespVO.ProgressStudentInfo student = new TeacherDashboardRespVO.ProgressStudentInfo();
            student.setStudentId(((Number) data.get("student_id")).longValue());
            student.setStudentName((String) data.get("student_name"));
            student.setStudentNo((String) data.get("student_no"));
            student.setCurrentScore(getBigDecimalFromMap(data, "currentScore"));
            student.setPreviousScore(getBigDecimalFromMap(data, "previousScore"));
            student.setProgressScore(getBigDecimalFromMap(data, "progressScore"));
            student.setRankImprovement(getIntegerFromMap(data, "rankImprovement"));

            // 分析升学层次变化
            BigDecimal currentScore = student.getCurrentScore();
            BigDecimal previousScore = student.getPreviousScore();
            if (currentScore != null && previousScore != null) {
                String currentLevel = getAdmissionLevel(currentScore);
                String previousLevel = getAdmissionLevel(previousScore);
                if (!currentLevel.equals(previousLevel)) {
                    student.setAdmissionLevelChange("从" + previousLevel + "提升到" + currentLevel);
                } else {
                    student.setAdmissionLevelChange("保持" + currentLevel + "层次");
                }
            }
            
            // 设置新增字段
            student.setSubjectCombination((String) data.get("subject_combination"));
            student.setExamType((String) data.get("exam_type"));
            student.setCurrentScoreAssigned(getBigDecimalFromMap(data, "current_score_assigned"));
            student.setPreviousScoreAssigned(getBigDecimalFromMap(data, "previous_score_assigned"));

            improvedStudents.add(student);
        }

        return improvedStudents;
    }

    @Override
    public List<TeacherDashboardRespVO.AttentionStudentInfo> getAttentionStudents(Long classId, Long currentExamId, Long previousExamId) {
        List<Map<String, Object>> attentionData = examScoreMapper.selectAttentionStudents(classId, currentExamId, previousExamId);
        List<TeacherDashboardRespVO.AttentionStudentInfo> attentionStudents = new ArrayList<>();

        for (Map<String, Object> data : attentionData) {
            TeacherDashboardRespVO.AttentionStudentInfo student = new TeacherDashboardRespVO.AttentionStudentInfo();
            student.setStudentId(((Number) data.get("student_id")).longValue());
            student.setStudentName((String) data.get("student_name"));
            student.setStudentNo((String) data.get("student_no"));
            student.setCurrentScore(getBigDecimalFromMap(data, "currentScore"));
            student.setScoreChange(getBigDecimalFromMap(data, "scoreChange"));
            student.setRankChange(getIntegerFromMap(data, "rankChange"));
            student.setAttentionReason((String) data.get("attentionReason"));

            // 根据关注原因提供建议措施
            String reason = student.getAttentionReason();
            if ("成绩大幅下滑".equals(reason)) {
                student.setSuggestedAction("立即进行一对一辅导，分析下滑原因");
            } else if ("成绩下滑".equals(reason)) {
                student.setSuggestedAction("加强薄弱科目辅导，关注学习状态");
            } else if ("排名靠后".equals(reason)) {
                student.setSuggestedAction("制定个性化提升计划，增强学习信心");
            } else {
                student.setSuggestedAction("密切关注学习动态");
            }
            
            // 设置新增字段
            student.setSubjectCombination((String) data.get("subject_combination"));
            student.setExamType((String) data.get("exam_type"));
            student.setCurrentScoreAssigned(getBigDecimalFromMap(data, "current_score_assigned"));
            student.setTotalUnionRank(getIntegerFromMap(data, "total_union_rank"));

            attentionStudents.add(student);
        }

        return attentionStudents;
    }

    @Override
    public TeacherDashboardRespVO.CriticalStudentAnalysis getCriticalStudentAnalysis(Long classId, Long examId, Integer range) {
        if (range == null || range <= 0) {
            range = 10;
        }

        // 获取科目类型（默认使用物理类）
        String subjectType = "物理类";
        try {
            // 尝试从考试数据中获取科目类型
            ExamScoreDO sampleScore = examScoreMapper.selectOne(new LambdaQueryWrapperX<ExamScoreDO>()
                .eq(ExamScoreDO::getExamId, examId)
                .last("LIMIT 1"));
            if (sampleScore != null) {
                subjectType = determineExamType(sampleScore);
            }
        } catch (Exception e) {
            log.warn("获取科目类型失败，使用默认值: {}", e.getMessage());
        }
        
        // 获取分数线配置
        Map<String, Integer> scoreLines = getScoreLineConfig(subjectType);
        List<Map<String, Object>> criticalData = examScoreMapper.selectCriticalStudents(classId, examId, range,
            scoreLines.get("score985"), scoreLines.get("score211"), 
            scoreLines.get("scoreFirstTier"), scoreLines.get("scoreSecondTier"),
            scoreLines.get("scoreUndergraduate"), 30);
        TeacherDashboardRespVO.CriticalStudentAnalysis analysis = new TeacherDashboardRespVO.CriticalStudentAnalysis();

        List<TeacherDashboardRespVO.CriticalStudentInfo> critical985 = new ArrayList<>();
        List<TeacherDashboardRespVO.CriticalStudentInfo> critical211 = new ArrayList<>();
        List<TeacherDashboardRespVO.CriticalStudentInfo> criticalFirst = new ArrayList<>();
        List<TeacherDashboardRespVO.CriticalStudentInfo> criticalSecond = new ArrayList<>();

        for (Map<String, Object> data : criticalData) {
            TeacherDashboardRespVO.CriticalStudentInfo student = new TeacherDashboardRespVO.CriticalStudentInfo();
            student.setStudentId(((Number) data.get("student_id")).longValue());
            student.setStudentName((String) data.get("student_name"));
            student.setStudentNo((String) data.get("student_no"));
            student.setCurrentScore(getBigDecimalFromMap(data, "total_score"));
            student.setScoreDiff(getBigDecimalFromMap(data, "scoreDiff"));

            // 设置新增字段
            student.setSubjectCombination((String) data.get("subject_combination"));
            student.setExamType((String) data.get("exam_type"));
            student.setCurrentScoreAssigned(getBigDecimalFromMap(data, "total_score_assigned"));
            
            String criticalType = (String) data.get("criticalType");
            if ("985临界".equals(criticalType)) {
                student.setTargetScore(BigDecimal.valueOf(680));
                student.setTargetScoreAssigned(BigDecimal.valueOf(685));
                student.setTargetLevel("985");
                student.setImprovementSuggestion("重点提升数学和理综成绩");
                critical985.add(student);
            } else if ("211临界".equals(criticalType)) {
                student.setTargetScore(BigDecimal.valueOf(650));
                student.setTargetScoreAssigned(BigDecimal.valueOf(655));
                student.setTargetLevel("211");
                student.setImprovementSuggestion("稳固基础，提升薄弱科目");
                critical211.add(student);
            } else if ("一本临界".equals(criticalType)) {
                student.setTargetScore(BigDecimal.valueOf(620));
                student.setTargetScoreAssigned(BigDecimal.valueOf(625));
                student.setTargetLevel("一本");
                student.setImprovementSuggestion("加强基础训练，避免失误");
                criticalFirst.add(student);
            } else if ("二本临界".equals(criticalType)) {
                student.setTargetScore(BigDecimal.valueOf(550));
                student.setTargetScoreAssigned(BigDecimal.valueOf(555));
                student.setTargetLevel("二本");
                student.setImprovementSuggestion("夯实基础知识，提升应试能力");
                criticalSecond.add(student);
            }
        }

        analysis.setCritical985Students(critical985);
        analysis.setCritical211Students(critical211);
        analysis.setCriticalFirstTierStudents(criticalFirst);
        analysis.setCriticalSecondTierStudents(criticalSecond);

        return analysis;
    }

    @Override
    public Integer getClassRankInGrade(Long classId, Long examId) {
        return examScoreMapper.selectClassRankInGrade(classId, examId);
    }

    /**
     * 根据分数判断升学层次
     */
    private String getAdmissionLevel(BigDecimal score) {
        if (score == null) {
            return "未知";
        }

        double scoreValue = score.doubleValue();
        if (scoreValue >= 680) {
            return "985";
        } else if (scoreValue >= 650) {
            return "211";
        } else if (scoreValue >= 620) {
            return "一本";
        } else if (scoreValue >= 550) {
            return "二本";
        } else if (scoreValue >= 400) {
            return "专科";
        } else {
            return "未达线";
        }
    }

    // ==================== 其他接口方法的简化实现 ====================

    @Override
    public TeacherDashboardRespVO.AdmissionTrendAnalysis getAdmissionTrendAnalysis(Long classId, Integer limit) {
        if (limit == null || limit <= 0) {
            limit = 5;
        }

        // 获取科目类型（默认使用物理类）
        String subjectType = "物理类";
        try {
            // 尝试从班级的最新考试数据中获取科目类型
            ExamScoreDO sampleScore = examScoreMapper.selectOne(new LambdaQueryWrapperX<ExamScoreDO>()
                .eq(ExamScoreDO::getClassId, classId)
                .orderByDesc(ExamScoreDO::getCreateTime)
                .last("LIMIT 1"));
            if (sampleScore != null) {
                subjectType = determineExamType(sampleScore);
            }
        } catch (Exception e) {
            log.warn("获取科目类型失败，使用默认值: {}", e.getMessage());
        }
        
        // 获取分数线配置
        Map<String, Integer> scoreLines = getScoreLineConfig(subjectType);
        List<Map<String, Object>> trendData = examScoreMapper.selectClassAdmissionTrend(classId, limit,
            scoreLines.get("score985"), scoreLines.get("score211"), scoreLines.get("scoreFirstTier"));
        TeacherDashboardRespVO.AdmissionTrendAnalysis analysis = new TeacherDashboardRespVO.AdmissionTrendAnalysis();

        List<TeacherDashboardRespVO.AdmissionTrendPoint> trendPoints = new ArrayList<>();
        for (Map<String, Object> data : trendData) {
            TeacherDashboardRespVO.AdmissionTrendPoint point = new TeacherDashboardRespVO.AdmissionTrendPoint();
            point.setExamName((String) data.get("exam_name"));
            point.setExamDate((LocalDateTime) data.get("exam_date"));
            point.setClassAvgScore(getBigDecimalFromMap(data, "classAvgScore"));
            point.setRate985(getBigDecimalFromMap(data, "rate985"));
            point.setRate211(getBigDecimalFromMap(data, "rate211"));
            point.setFirstTierRate(getBigDecimalFromMap(data, "firstTierRate"));
            trendPoints.add(point);
        }
        analysis.setTrendPoints(trendPoints);

        // 简化的趋势分析
        if (trendPoints.size() >= 2) {
            BigDecimal firstRate = trendPoints.get(0).getFirstTierRate();
            BigDecimal lastRate = trendPoints.get(trendPoints.size() - 1).getFirstTierRate();
            if (firstRate != null && lastRate != null) {
                BigDecimal change = firstRate.subtract(lastRate);
                analysis.setChangeRate(change);
                if (change.compareTo(BigDecimal.ZERO) > 0) {
                    analysis.setOverallTrend("上升");
                } else if (change.compareTo(BigDecimal.ZERO) < 0) {
                    analysis.setOverallTrend("下降");
                } else {
                    analysis.setOverallTrend("稳定");
                }
            }
        }

        return analysis;
    }

    @Override
    public TeacherDashboardRespVO.ComparisonAnalysis getComparisonAnalysis(Long classId, Long examId) {
        TeacherDashboardRespVO.ComparisonAnalysis analysis = new TeacherDashboardRespVO.ComparisonAnalysis();

        // 获取科目类型（默认使用物理类）
        String subjectType = "物理类";
        try {
            // 尝试从指定考试的班级数据中获取科目类型
            ExamScoreDO sampleScore = examScoreMapper.selectOne(new LambdaQueryWrapperX<ExamScoreDO>()
                .eq(ExamScoreDO::getClassId, classId)
                .eq(ExamScoreDO::getExamId, examId)
                .last("LIMIT 1"));
            if (sampleScore != null) {
                subjectType = determineExamType(sampleScore);
            }
        } catch (Exception e) {
            log.warn("获取科目类型失败，使用默认值: {}", e.getMessage());
        }
        
        // 获取分数线配置
        Map<String, Integer> scoreLines = getScoreLineConfig(subjectType);
        
        // 获取班级对比信息
        List<Map<String, Object>> comparisonData = examScoreMapper.selectClassComparison(classId, examId, 
            scoreLines.get("scoreFirstTier"));
        TeacherDashboardRespVO.ClassComparisonInfo classComparison = new TeacherDashboardRespVO.ClassComparisonInfo();

        // 找到当前班级的数据
        for (Map<String, Object> data : comparisonData) {
            // 这里简化处理，实际需要根据班级名称匹配
            classComparison.setAvgScoreRank(getIntegerFromMap(data, "avgScoreRank"));
            classComparison.setFirstTierRateRank(getIntegerFromMap(data, "firstTierRateRank"));
            break; // 简化处理
        }

        classComparison.setTotalClasses(comparisonData.size());
        classComparison.setGradeRank(getClassRankInGrade(classId, examId));
        analysis.setClassComparison(classComparison);

        return analysis;
    }

    @Override
    public TeacherDashboardRespVO.TeachingEffectAnalysis getTeachingEffectAnalysis(Long classId, Long currentExamId, Long previousExamId) {
        TeacherDashboardRespVO.TeachingEffectAnalysis analysis = new TeacherDashboardRespVO.TeachingEffectAnalysis();

        // 获取当前和上次考试的统计数据
        Map<String, Object> currentStats = examScoreMapper.selectClassScoreStatistics(classId, currentExamId);
        Map<String, Object> previousStats = examScoreMapper.selectClassScoreStatistics(classId, previousExamId);

        // 计算提分效果
        TeacherDashboardRespVO.ScoreImprovementEffect improvement = new TeacherDashboardRespVO.ScoreImprovementEffect();
        if (currentStats != null && previousStats != null) {
            BigDecimal currentAvg = getBigDecimalFromMap(currentStats, "avgScore");
            BigDecimal previousAvg = getBigDecimalFromMap(previousStats, "avgScore");
            if (currentAvg != null && previousAvg != null) {
                improvement.setAvgScoreImprovement(currentAvg.subtract(previousAvg));
            }
        }

        // 获取进步学生数据
        List<TeacherDashboardRespVO.ProgressStudentInfo> improvedStudents = getMostImprovedStudents(classId, currentExamId, previousExamId, 50);
        improvement.setImprovedStudentCount(improvedStudents.size());

        // 计算提分率（简化处理）
        if (currentStats != null) {
            Object totalCountObj = currentStats.get("totalCount");
            if (totalCountObj != null && totalCountObj instanceof Number) {
                int totalCount = ((Number) totalCountObj).intValue();
                if (totalCount > 0) {
                    improvement.setImprovementRate(BigDecimal.valueOf(100.0 * improvedStudents.size() / totalCount).setScale(1, RoundingMode.HALF_UP));
                }
            }
        }

        analysis.setScoreImprovement(improvement);

        return analysis;
    }

    @Override
    public List<AdmissionAnalysisRespVO.StudentAdmissionDetail> getStudentAdmissionDetails(Long classId, Long examId) {
        // 获取科目类型（默认使用物理类）
        String subjectType = "物理类";
        try {
            // 尝试从指定考试的班级数据中获取科目类型
            ExamScoreDO sampleScore = examScoreMapper.selectOne(new LambdaQueryWrapperX<ExamScoreDO>()
                .eq(ExamScoreDO::getClassId, classId)
                .eq(ExamScoreDO::getExamId, examId)
                .last("LIMIT 1"));
            if (sampleScore != null) {
                subjectType = determineExamType(sampleScore);
            }
        } catch (Exception e) {
            log.warn("获取科目类型失败，使用默认值: {}", e.getMessage());
        }
        
        // 获取分数线配置
        Map<String, Integer> scoreLines = getScoreLineConfig(subjectType);
        List<Map<String, Object>> detailsData = examScoreMapper.selectStudentAdmissionDetails(classId, examId,
            scoreLines.get("score985"), scoreLines.get("score211"), scoreLines.get("scoreFirstTier"), 
            scoreLines.get("scoreSecondTier"), scoreLines.get("scoreSpecialist"));
        List<AdmissionAnalysisRespVO.StudentAdmissionDetail> details = new ArrayList<>();

        for (Map<String, Object> data : detailsData) {
            AdmissionAnalysisRespVO.StudentAdmissionDetail detail = new AdmissionAnalysisRespVO.StudentAdmissionDetail();
            detail.setStudentId(((Number) data.get("student_id")).longValue());
            detail.setStudentName((String) data.get("student_name"));
            detail.setStudentNo((String) data.get("student_no"));
            detail.setCurrentScore(getBigDecimalFromMap(data, "total_score"));
            detail.setPredictedGaokaoScore(getBigDecimalFromMap(data, "predictedGaokaoScore"));
            detail.setPredictedAdmissionLevel((String) data.get("predictedAdmissionLevel"));

            // 根据预测层次设置可报考大学（示例数据）
            String level = detail.getPredictedAdmissionLevel();
            switch (level) {
                case "985":
                    detail.setEligibleUniversities(Arrays.asList("清华大学", "北京大学", "复旦大学"));
                    detail.setStretchUniversities(Arrays.asList("清华大学", "北京大学"));
                    detail.setSafeUniversities(Arrays.asList("复旦大学", "上海交通大学"));
                    detail.setGuaranteedUniversities(Arrays.asList("中山大学", "华南理工大学"));
                    break;
                case "211":
                    detail.setEligibleUniversities(Arrays.asList("中山大学", "华南理工大学", "暨南大学"));
                    detail.setStretchUniversities(Arrays.asList("中山大学", "华南理工大学"));
                    detail.setSafeUniversities(Arrays.asList("暨南大学", "华南师范大学"));
                    detail.setGuaranteedUniversities(Arrays.asList("深圳大学", "广东工业大学"));
                    break;
                default:
                    detail.setEligibleUniversities(Arrays.asList("深圳大学", "广东工业大学"));
                    detail.setSafeUniversities(Arrays.asList("广东工业大学", "广东财经大学"));
                    detail.setGuaranteedUniversities(Arrays.asList("广东技术师范大学"));
                    break;
            }

            details.add(detail);
        }

        return details;
    }

    // 注意：generateAlerts方法已被移除，因为AlertInfo类在优化过程中被删除
    // 相关功能已整合到教学建议(TeachingSuggestion)中

    // ==================== 升学分析相关的辅助方法 ====================

    private TeacherDashboardRespVO.AdmissionAnalysis getAdmissionAnalysisInfo(Long classId, Long examId) {
        TeacherDashboardRespVO.AdmissionAnalysis analysis = new TeacherDashboardRespVO.AdmissionAnalysis();

        if (classId != null) {
            // 班级视图：获取特定班级的升学分析
            analysis.setPredictionStats(getAdmissionPredictionStats(classId, examId));
            analysis.setCriticalStudents(getCriticalStudentAnalysis(classId, examId, 10));
            analysis.setTrendAnalysis(getAdmissionTrendAnalysis(classId, 5));
        } else {
            // 全考试视图：获取全考试的升学分析
            analysis.setPredictionStats(getGlobalAdmissionPredictionStats(examId));
            analysis.setCriticalStudents(getGlobalCriticalStudentAnalysis(examId, 10));
            analysis.setTrendAnalysis(getGlobalAdmissionTrendAnalysis(examId, 5));
        }

        return analysis;
    }

    private TeacherDashboardRespVO.StudentRankingInfo getStudentRankingInfo(Long classId, Long examId) {
        TeacherDashboardRespVO.StudentRankingInfo rankingInfo = new TeacherDashboardRespVO.StudentRankingInfo();

        // 获取所有学生排名数据
        rankingInfo.setTopStudents(getTopStudents(classId, examId, null));

        // 这里可以添加更多排名相关的信息

        return rankingInfo;
    }

    // 升学分析相关的转换方法
    private AdmissionAnalysisRespVO.AdmissionPredictionStats convertToAdmissionPredictionStats(Long classId, Long examId) {
        TeacherDashboardRespVO.AdmissionPredictionStats stats = getAdmissionPredictionStats(classId, examId);

        AdmissionAnalysisRespVO.AdmissionPredictionStats result = new AdmissionAnalysisRespVO.AdmissionPredictionStats();
        result.setPredicted985Count(stats.getPredicted985Count());
        result.setPredicted985Rate(stats.getPredicted985Rate());
        result.setPredicted211Count(stats.getPredicted211Count());
        result.setPredicted211Rate(stats.getPredicted211Rate());
        result.setPredictedFirstTierCount(stats.getPredictedFirstTierCount());
        result.setPredictedFirstTierRate(stats.getPredictedFirstTierRate());
        result.setPredictedSecondTierCount(stats.getPredictedSecondTierCount());
        result.setPredictedSecondTierRate(stats.getPredictedSecondTierRate());
        result.setPredictedSpecialtyCount(stats.getPredictedSpecialtyCount());
        result.setPredictedSpecialtyRate(stats.getPredictedSpecialtyRate());
        result.setBelowLineCount(stats.getBelowLineCount());
        result.setBelowLineRate(stats.getBelowLineRate());

        return result;
    }

    private AdmissionAnalysisRespVO.CriticalStudentAnalysis getCriticalStudentAnalysisForAdmission(Long classId, Long examId, Integer range) {
        TeacherDashboardRespVO.CriticalStudentAnalysis analysis = getCriticalStudentAnalysis(classId, examId, range);

        AdmissionAnalysisRespVO.CriticalStudentAnalysis result = new AdmissionAnalysisRespVO.CriticalStudentAnalysis();
        result.setCritical985Students(convertCriticalStudents(analysis.getCritical985Students()));
        result.setCritical211Students(convertCriticalStudents(analysis.getCritical211Students()));
        result.setCriticalFirstTierStudents(convertCriticalStudents(analysis.getCriticalFirstTierStudents()));
        result.setCriticalSecondTierStudents(convertCriticalStudents(analysis.getCriticalSecondTierStudents()));

        // 计算总数和占比
        int totalCritical = analysis.getCritical985Students().size() +
                           analysis.getCritical211Students().size() +
                           analysis.getCriticalFirstTierStudents().size() +
                           analysis.getCriticalSecondTierStudents().size();
        result.setTotalCriticalStudents(totalCritical);

        return result;
    }

    private List<AdmissionAnalysisRespVO.CriticalStudentInfo> convertCriticalStudents(List<TeacherDashboardRespVO.CriticalStudentInfo> students) {
        List<AdmissionAnalysisRespVO.CriticalStudentInfo> result = new ArrayList<>();
        for (TeacherDashboardRespVO.CriticalStudentInfo student : students) {
            AdmissionAnalysisRespVO.CriticalStudentInfo converted = new AdmissionAnalysisRespVO.CriticalStudentInfo();
            converted.setStudentId(student.getStudentId());
            converted.setStudentName(student.getStudentName());
            converted.setStudentNo(student.getStudentNo());
            converted.setCurrentScore(student.getCurrentScore());
            converted.setTargetScore(student.getTargetScore());
            converted.setScoreDiff(student.getScoreDiff());
            converted.setTargetLevel(student.getTargetLevel());
            converted.setImprovementSuggestion(student.getImprovementSuggestion());
            converted.setImprovementPossibility("中等"); // 简化处理
            result.add(converted);
        }
        return result;
    }

    private AdmissionAnalysisRespVO.TargetAchievementInfo getTargetAchievementInfoForAdmission(Long classId, Long examId) {
        // 简化实现，返回基本的目标达成信息
        AdmissionAnalysisRespVO.TargetAchievementInfo info = new AdmissionAnalysisRespVO.TargetAchievementInfo();

        AdmissionAnalysisRespVO.ClassTargetInfo classTarget = new AdmissionAnalysisRespVO.ClassTargetInfo();
        classTarget.setFirstTierTargetCount(36);
        classTarget.setFirstTierTargetRate(BigDecimal.valueOf(80.0));
        classTarget.setTarget985Count(10);
        classTarget.setTarget985Rate(BigDecimal.valueOf(22.2));
        classTarget.setTarget211Count(18);
        classTarget.setTarget211Rate(BigDecimal.valueOf(40.0));
        info.setClassTarget(classTarget);

        return info;
    }

    private AdmissionAnalysisRespVO.AdmissionTrendAnalysis getAdmissionTrendAnalysisForAdmission(Long classId, Integer limit) {
        TeacherDashboardRespVO.AdmissionTrendAnalysis analysis = getAdmissionTrendAnalysis(classId, limit);

        AdmissionAnalysisRespVO.AdmissionTrendAnalysis result = new AdmissionAnalysisRespVO.AdmissionTrendAnalysis();
        result.setOverallTrend(analysis.getOverallTrend());
        result.setFirstTierRateChange(analysis.getChangeRate());

        // 转换趋势点
        List<AdmissionAnalysisRespVO.AdmissionTrendPoint> trendPoints = new ArrayList<>();
        for (TeacherDashboardRespVO.AdmissionTrendPoint point : analysis.getTrendPoints()) {
            AdmissionAnalysisRespVO.AdmissionTrendPoint converted = new AdmissionAnalysisRespVO.AdmissionTrendPoint();
            converted.setExamName(point.getExamName());
            converted.setExamDate(point.getExamDate());
            converted.setFirstTierRate(point.getFirstTierRate());
            converted.setRate985(point.getRate985());
            converted.setRate211(point.getRate211());
            converted.setClassAvgScore(point.getClassAvgScore());
            trendPoints.add(converted);
        }
        result.setTrendPoints(trendPoints);

        return result;
    }

    /**
     * 获取重点关注学生
     */
    private List<TeacherDashboardRespVO.FocusStudent> getFocusStudents(Long classId, Long examId) {
        List<TeacherDashboardRespVO.FocusStudent> focusStudents = new ArrayList<>();
        
        try {
            // 获取科目类型（默认使用物理类）
            String subjectType = "物理类";
            try {
                // 尝试从考试数据中获取科目类型
                ExamScoreDO sampleScore = examScoreMapper.selectOne(new LambdaQueryWrapperX<ExamScoreDO>()
                    .eq(ExamScoreDO::getExamId, examId)
                    .last("LIMIT 1"));
                if (sampleScore != null) {
                    subjectType = determineExamType(sampleScore);
                }
            } catch (Exception e) {
                log.warn("获取科目类型失败，使用默认值: {}", e.getMessage());
            }
            
            // 获取分数线配置
            Map<String, Integer> scoreLines = getScoreLineConfig(subjectType);
            // 获取临界学生（距离各分数线10分以内，本科线30分以内用于识别"即将达本"学生）
            List<Map<String, Object>> criticalStudents = examScoreMapper.selectCriticalStudents(classId, examId, 10,
                scoreLines.get("score985"), scoreLines.get("score211"), 
                scoreLines.get("scoreFirstTier"), scoreLines.get("scoreSecondTier"),
                scoreLines.get("scoreUndergraduate"), 30);
            for (Map<String, Object> student : criticalStudents) {
                String criticalType = (String) student.get("criticalType");
                if (criticalType != null) {
                    TeacherDashboardRespVO.FocusStudent focusStudent = createFocusStudent(student, criticalType, scoreLines);
                    if (focusStudent != null) {
                        focusStudents.add(focusStudent);
                    }
                }
            }
            
            // 获取需要关注的学生（成绩下滑等）
            // 这里可以添加更多关注学生的逻辑
            
        } catch (Exception e) {
            log.error("获取重点关注学生失败，班级ID: {}, 考试ID: {}", classId, examId, e);
        }
        
        // 限制返回数量，避免数据过多
        return focusStudents.stream().limit(10).collect(Collectors.toList());
    }
    
    /**
     * 创建重点关注学生对象
     */
    private TeacherDashboardRespVO.FocusStudent createFocusStudent(Map<String, Object> studentData, String criticalType, Map<String, Integer> scoreLines) {
        try {
            TeacherDashboardRespVO.FocusStudent focusStudent = new TeacherDashboardRespVO.FocusStudent();
            focusStudent.setStudentId(getLongFromMap(studentData, "student_id"));
            focusStudent.setStudentName((String) studentData.get("student_name"));
            focusStudent.setStudentNo((String) studentData.get("student_no"));
            focusStudent.setCurrentScore(getBigDecimalFromMap(studentData, "total_score"));
            
            // 根据临界类型设置相关信息，使用动态分数线配置
            switch (criticalType) {
                case "985临界":
                    focusStudent.setFocusType("临界985");
                    focusStudent.setTargetScore(BigDecimal.valueOf(scoreLines.get("score985")));
                    focusStudent.setFocusReason("距离985线较近，有冲击可能");
                    break;
                case "211临界":
                    focusStudent.setFocusType("临界211");
                    focusStudent.setTargetScore(BigDecimal.valueOf(scoreLines.get("score211")));
                    focusStudent.setFocusReason("距离211线较近，需要重点关注");
                    break;
                case "一本临界":
                    focusStudent.setFocusType("临界一本");
                    focusStudent.setTargetScore(BigDecimal.valueOf(scoreLines.get("scoreFirstTier")));
                    focusStudent.setFocusReason("距离一本线较近，需要加强辅导");
                    break;
                case "二本临界":
                    focusStudent.setFocusType("临界二本");
                    focusStudent.setTargetScore(BigDecimal.valueOf(scoreLines.get("scoreSecondTier")));
                    focusStudent.setFocusReason("距离二本线较近，需要稳固基础");
                    break;
                case "本科临界":
                    focusStudent.setFocusType("即将达本");
                    focusStudent.setTargetScore(BigDecimal.valueOf(scoreLines.get("scoreUndergraduate")));
                    focusStudent.setFocusReason("距离本科线较近，需要重点辅导冲刺达本");
                    break;
                default:
                    focusStudent.setFocusType("需要关注");
                    focusStudent.setFocusReason("成绩波动较大，需要关注");
                    break;
            }
            
            // 计算分数差距
            if (focusStudent.getCurrentScore() != null && focusStudent.getTargetScore() != null) {
                focusStudent.setScoreDiff(focusStudent.getTargetScore().subtract(focusStudent.getCurrentScore()));
            }
            
            // 生成建议措施
            focusStudent.setSuggestion(generateStudentSuggestion(focusStudent));
            
            return focusStudent;
        } catch (Exception e) {
            log.error("创建重点关注学生对象失败", e);
            return null;
        }
    }
    
    /**
     * 生成学生建议措施
     */
    private String generateStudentSuggestion(TeacherDashboardRespVO.FocusStudent student) {
        if (student.getScoreDiff() == null) {
            return "需要全面提升各科成绩";
        }
        
        BigDecimal diff = student.getScoreDiff();
        if (diff.compareTo(BigDecimal.valueOf(5)) <= 0) {
            return "距离目标很近，重点突破薄弱环节";
        } else if (diff.compareTo(BigDecimal.valueOf(15)) <= 0) {
            return "需要稳步提升，重点关注主要科目";
        } else {
            return "需要全面加强，制定详细提升计划";
        }
    }
    
    /**
     * 生成教学建议
     */
    private List<TeacherDashboardRespVO.TeachingSuggestion> generateTeachingSuggestions(Long classId, Long examId) {
        List<TeacherDashboardRespVO.TeachingSuggestion> suggestions = new ArrayList<>();
        
        try {
            // 基于成绩统计生成科目建议
            TeacherDashboardRespVO.ScoreStatistics scoreStats;
            if (classId != null) {
                scoreStats = getClassScoreStatistics(classId, examId);
            } else {
                // 校领导全考试视图，使用全考试统计
                scoreStats = getGlobalScoreStatistics(examId);
            }
            
            if (scoreStats != null && scoreStats.getSubjectScores() != null) {
                for (TeacherDashboardRespVO.SubjectScoreStats subjectStats : scoreStats.getSubjectScores().values()) {
                    if (subjectStats.getPassRate() != null && subjectStats.getPassRate().compareTo(BigDecimal.valueOf(80)) < 0) {
                        TeacherDashboardRespVO.TeachingSuggestion suggestion = new TeacherDashboardRespVO.TeachingSuggestion();
                        suggestion.setSuggestionType("科目提升");
                        suggestion.setPriority("高");
                        String scope = classId != null ? "班级" : "全年级";
                        suggestion.setContent(subjectStats.getSubjectName() + "科目" + scope + "及格率偏低，需要加强基础训练");
                        suggestion.setSpecificActions("增加" + subjectStats.getSubjectName() + "课后辅导，重点训练基础题型");
                        suggestion.setExpectedEffect("预计可提升及格率10-15%");
                        suggestions.add(suggestion);
                    }
                }
            }
            
            // 基于升学预测生成目标建议
            TeacherDashboardRespVO.AdmissionPredictionStats admissionStats = getAdmissionPredictionStats(classId, examId);
            if (admissionStats != null) {
                if (admissionStats.getPredictedFirstTierRate() != null && 
                    admissionStats.getPredictedFirstTierRate().compareTo(BigDecimal.valueOf(70)) < 0) {
                    TeacherDashboardRespVO.TeachingSuggestion suggestion = new TeacherDashboardRespVO.TeachingSuggestion();
                    suggestion.setSuggestionType("目标调整");
                    suggestion.setPriority("中");
                    String scope = classId != null ? "班级" : "全年级";
                    suggestion.setContent(scope + "一本上线率需要提升，建议加强临界学生辅导");
                    suggestion.setSpecificActions("针对临界学生制定个性化提升方案");
                    suggestion.setExpectedEffect("预计可提升一本上线率5-10%");
                    suggestions.add(suggestion);
                }
            }
            
            // 添加通用教学建议
            if (suggestions.isEmpty()) {
                TeacherDashboardRespVO.TeachingSuggestion suggestion = new TeacherDashboardRespVO.TeachingSuggestion();
                suggestion.setSuggestionType("教学策略");
                suggestion.setPriority("中");
                suggestion.setContent("继续保持良好的教学状态，关注学生个体差异");
                suggestion.setSpecificActions("定期进行学情分析，及时调整教学策略");
                suggestion.setExpectedEffect("维持班级整体稳定发展");
                suggestions.add(suggestion);
            }
            
        } catch (Exception e) {
            log.error("生成教学建议失败，班级ID: {}, 考试ID: {}", classId, examId, e);
        }
        
        return suggestions;
    }
    
    /**
     * 从Map中安全获取Long值
     */
    private Long getLongFromMap(Map<String, Object> map, String key) {
        Object value = map.get(key);
        if (value == null) {
            return null;
        }
        if (value instanceof Number) {
            return ((Number) value).longValue();
        }
        try {
            return Long.valueOf(value.toString());
        } catch (NumberFormatException e) {
            return null;
        }
    }

    // ==================== 默认值创建方法 ====================

    /**
     * 创建默认班级信息
     */
    private TeacherDashboardRespVO.ClassBasicInfo createDefaultClassInfo(Long classId) {
        TeacherDashboardRespVO.ClassBasicInfo classInfo = new TeacherDashboardRespVO.ClassBasicInfo();
        classInfo.setClassId(classId);
        classInfo.setClassName("班级" + classId);
        classInfo.setGrade("高三");
        classInfo.setTotalStudents(0);
        classInfo.setTeacherName("班主任");
        classInfo.setClassType("普通班");
        classInfo.setClassTarget("努力提升班级成绩");
        return classInfo;
    }

    /**
     * 创建默认考试概况
     */
    private TeacherDashboardRespVO.LatestExamOverview createDefaultExamOverview(Long examId) {
        TeacherDashboardRespVO.LatestExamOverview overview = new TeacherDashboardRespVO.LatestExamOverview();
        overview.setExamId(examId);
        overview.setExamName("考试" + examId);
        overview.setExamDate(LocalDateTime.now());
        overview.setParticipantCount(0);
        overview.setAbsentCount(0);
        overview.setClassAvgScore(BigDecimal.ZERO);
        overview.setClassMaxScore(BigDecimal.ZERO);
        overview.setClassMinScore(BigDecimal.ZERO);
        overview.setGradeAvgScore(BigDecimal.ZERO);
        overview.setClassRankInGrade(1);
        overview.setTotalClassesInGrade(1);
        return overview;
    }

    /**
     * 创建默认成绩统计
     */
    private TeacherDashboardRespVO.ScoreStatistics createDefaultScoreStatistics() {
        TeacherDashboardRespVO.ScoreStatistics statistics = new TeacherDashboardRespVO.ScoreStatistics();
        
        // 默认总分统计
        TeacherDashboardRespVO.TotalScoreStats totalStats = new TeacherDashboardRespVO.TotalScoreStats();
        totalStats.setAvgScore(BigDecimal.ZERO);
        totalStats.setMaxScore(BigDecimal.ZERO);
        totalStats.setMinScore(BigDecimal.ZERO);
        totalStats.setStandardDeviation(BigDecimal.ZERO);
        totalStats.setGradeAvgDiff(BigDecimal.ZERO);
        totalStats.setGradeRank(1);
        statistics.setTotalScore(totalStats);
        
        // 默认科目成绩
        Map<String, TeacherDashboardRespVO.SubjectScoreStats> subjectScores = new HashMap<>();
        String[] subjects = {"语文", "数学", "英语"};
        for (String subject : subjects) {
            TeacherDashboardRespVO.SubjectScoreStats subjectStats = new TeacherDashboardRespVO.SubjectScoreStats();
            subjectStats.setSubjectName(subject);
            subjectStats.setAvgScore(BigDecimal.ZERO);
            subjectStats.setMaxScore(BigDecimal.ZERO);
            subjectStats.setMinScore(BigDecimal.ZERO);
            subjectStats.setFullScore(BigDecimal.valueOf(150));
            subjectStats.setPassRate(BigDecimal.ZERO);
            subjectStats.setExcellentRate(BigDecimal.ZERO);
            subjectStats.setGradeAvgDiff(BigDecimal.ZERO);
            subjectStats.setGradeRank(1);
            subjectScores.put(subject, subjectStats);
        }
        statistics.setSubjectScores(subjectScores);
        
        // 默认分数段分布
        statistics.setScoreDistribution(new ArrayList<>());
        
        // 默认及格率统计
        TeacherDashboardRespVO.PassRateStats passRateStats = new TeacherDashboardRespVO.PassRateStats();
        passRateStats.setOverallPassRate(BigDecimal.ZERO);
        passRateStats.setExcellentRate(BigDecimal.ZERO);
        passRateStats.setGoodRate(BigDecimal.ZERO);
        passRateStats.setFailRate(BigDecimal.ZERO);
        passRateStats.setSubjectPassRates(new HashMap<>());
        statistics.setPassRate(passRateStats);
        
        return statistics;
    }

    /**
     * 创建默认升学分析
     */
    private TeacherDashboardRespVO.AdmissionAnalysis createDefaultAdmissionAnalysis() {
        TeacherDashboardRespVO.AdmissionAnalysis analysis = new TeacherDashboardRespVO.AdmissionAnalysis();
        
        // 默认升学预测统计
        TeacherDashboardRespVO.AdmissionPredictionStats predictionStats = new TeacherDashboardRespVO.AdmissionPredictionStats();
        predictionStats.setPredicted985Count(0);
        predictionStats.setPredicted985Rate(BigDecimal.ZERO);
        predictionStats.setPredicted211Count(0);
        predictionStats.setPredicted211Rate(BigDecimal.ZERO);
        predictionStats.setPredictedFirstTierCount(0);
        predictionStats.setPredictedFirstTierRate(BigDecimal.ZERO);
        predictionStats.setPredictedSecondTierCount(0);
        predictionStats.setPredictedSecondTierRate(BigDecimal.ZERO);
        predictionStats.setPredictedSpecialtyCount(0);
        predictionStats.setPredictedSpecialtyRate(BigDecimal.ZERO);
        predictionStats.setBelowLineCount(0);
        predictionStats.setBelowLineRate(BigDecimal.ZERO);
        analysis.setPredictionStats(predictionStats);
        
        // 默认目标达成情况
        TeacherDashboardRespVO.TargetAchievementInfo targetAchievement = new TeacherDashboardRespVO.TargetAchievementInfo();
        targetAchievement.setClassTarget("暂无目标设定");
        targetAchievement.setTargetCount(0);
        targetAchievement.setCurrentPredictedCount(0);
        targetAchievement.setAchievementRate(BigDecimal.ZERO);
        targetAchievement.setGapToTarget(0);
        targetAchievement.setAchievementStatus("待评估");
        analysis.setTargetAchievement(targetAchievement);
        
        // 默认临界学生分析
        TeacherDashboardRespVO.CriticalStudentAnalysis criticalStudents = new TeacherDashboardRespVO.CriticalStudentAnalysis();
        criticalStudents.setCritical985Students(new ArrayList<>());
        criticalStudents.setCritical211Students(new ArrayList<>());
        criticalStudents.setCriticalFirstTierStudents(new ArrayList<>());
        criticalStudents.setCriticalSecondTierStudents(new ArrayList<>());
        analysis.setCriticalStudents(criticalStudents);
        
        // 默认趋势分析
        TeacherDashboardRespVO.AdmissionTrendAnalysis trendAnalysis = new TeacherDashboardRespVO.AdmissionTrendAnalysis();
        trendAnalysis.setTrendPoints(new ArrayList<>());
        trendAnalysis.setOverallTrend("稳定");
        trendAnalysis.setChangeRate(BigDecimal.ZERO);
        analysis.setTrendAnalysis(trendAnalysis);
        
        return analysis;
    }

    /**
     * 创建默认学生排名信息
     */
    private TeacherDashboardRespVO.StudentRankingInfo createDefaultStudentRanking() {
        TeacherDashboardRespVO.StudentRankingInfo rankingInfo = new TeacherDashboardRespVO.StudentRankingInfo();
        rankingInfo.setTopStudents(new ArrayList<>());
        rankingInfo.setMostImprovedStudents(new ArrayList<>());
        rankingInfo.setAttentionStudents(new ArrayList<>());
        
        // 默认排名变化统计
        TeacherDashboardRespVO.RankingChangeStats changeStats = new TeacherDashboardRespVO.RankingChangeStats();
        changeStats.setRankUpCount(0);
        changeStats.setRankDownCount(0);
        changeStats.setRankSameCount(0);
        changeStats.setAvgRankChange(BigDecimal.ZERO);
        rankingInfo.setRankingChangeStats(changeStats);
        
        return rankingInfo;
    }

    /**
     * 创建默认对比分析
     */
    private TeacherDashboardRespVO.ComparisonAnalysis createDefaultComparison() {
        TeacherDashboardRespVO.ComparisonAnalysis comparison = new TeacherDashboardRespVO.ComparisonAnalysis();
        
        // 默认班级对比
        TeacherDashboardRespVO.ClassComparisonInfo classComparison = new TeacherDashboardRespVO.ClassComparisonInfo();
        classComparison.setGradeRank(1);
        classComparison.setTotalClasses(1);
        classComparison.setAvgScoreRank(1);
        classComparison.setFirstTierRateRank(1);
        classComparison.setGapToFirst(BigDecimal.ZERO);
        comparison.setClassComparison(classComparison);
        
        // 默认历史对比
        comparison.setHistoricalComparison(null);
        
        // 默认科目对比
        comparison.setSubjectComparison(new HashMap<>());
        
        return comparison;
    }

    /**
     * 创建默认教学建议
     */
    private List<TeacherDashboardRespVO.TeachingSuggestion> createDefaultTeachingSuggestions() {
        List<TeacherDashboardRespVO.TeachingSuggestion> suggestions = new ArrayList<>();
        
        TeacherDashboardRespVO.TeachingSuggestion suggestion = new TeacherDashboardRespVO.TeachingSuggestion();
        suggestion.setSuggestionType("教学策略");
        suggestion.setPriority("中");
        suggestion.setContent("继续保持良好的教学状态，关注学生个体差异");
        suggestion.setAffectedStudentCount(0);
        suggestion.setExpectedEffect("维持班级整体稳定发展");
        suggestion.setSpecificActions("定期进行学情分析，及时调整教学策略");
        suggestions.add(suggestion);
        
        return suggestions;
    }

    /**
     * 获取动态分数线配置（兼容旧方法，使用默认省份和年份）
     */
    private Map<String, Integer> getScoreLineConfig(String subjectType) {
        return getScoreLineConfig(subjectType, "安徽", 2025);
    }

    /**
     * 获取动态分数线配置
     */
    private Map<String, Integer> getScoreLineConfig(String subjectType, String province, Integer year) {
        Map<String, Integer> scoreLines = new HashMap<>();
        
        try {
            // 获取985分数线
            Integer score985 = scoreLineConfigService.getScoreByConfigTypeAndSubjectTypeAndProvinceAndYear("985", subjectType, province, year);
            scoreLines.put("score985", score985 != null ? score985 : 680);
            
            // 获取211分数线
            Integer score211 = scoreLineConfigService.getScoreByConfigTypeAndSubjectTypeAndProvinceAndYear("211", subjectType, province, year);
            scoreLines.put("score211", score211 != null ? score211 : 590);
            
            // 获取一本分数线
            Integer scoreFirstTier = scoreLineConfigService.getScoreByConfigTypeAndSubjectTypeAndProvinceAndYear("FIRST_TIER", subjectType, province, year);
            scoreLines.put("scoreFirstTier", scoreFirstTier != null ? scoreFirstTier : 514);
            
            // 获取二本分数线
            Integer scoreSecondTier = scoreLineConfigService.getScoreByConfigTypeAndSubjectTypeAndProvinceAndYear("SECOND_TIER", subjectType, province, year);
            scoreLines.put("scoreSecondTier", scoreSecondTier != null ? scoreSecondTier : 461);
            
            // 获取专科分数线
            Integer scoreSpecialist = scoreLineConfigService.getScoreByConfigTypeAndSubjectTypeAndProvinceAndYear("SPECIALIST", subjectType, province, year);
            scoreLines.put("scoreSpecialist", scoreSpecialist != null ? scoreSpecialist : 200);
            
            // 获取双一流分数线
            Integer scoreDoubleFirst = scoreLineConfigService.getScoreByConfigTypeAndSubjectTypeAndProvinceAndYear("DOUBLE_FIRST", subjectType, province, year);
            scoreLines.put("scoreDoubleFirst", scoreDoubleFirst != null ? scoreDoubleFirst : 630);
            
            // 获取特控线
            Integer scoreSpecialControl = scoreLineConfigService.getScoreByConfigTypeAndSubjectTypeAndProvinceAndYear("SPECIAL_CONTROL", subjectType, province, year);
            scoreLines.put("scoreSpecialControl", scoreSpecialControl != null ? scoreSpecialControl : 
                ("物理类".equals(subjectType) ? 518 : 520));
            
            // 获取本科线
            Integer scoreUndergraduate = scoreLineConfigService.getScoreByConfigTypeAndSubjectTypeAndProvinceAndYear("UNDERGRADUATE", subjectType, province, year);
            scoreLines.put("scoreUndergraduate", scoreUndergraduate != null ? scoreUndergraduate : 
                ("物理类".equals(subjectType) ? 461 : 467));
            
        } catch (Exception e) {
            log.warn("获取动态分数线配置失败，使用默认值: {}", e.getMessage());
            // 使用默认分数线
            scoreLines.put("score985", 680);
            scoreLines.put("score211", 650);
            scoreLines.put("scoreFirstTier", 620);
            scoreLines.put("scoreSecondTier", 550);
            scoreLines.put("scoreSpecialist", 400);
            scoreLines.put("scoreDoubleFirst", 630);
            scoreLines.put("scoreSpecialControl", "物理类".equals(subjectType) ? 518 : 520);
            scoreLines.put("scoreUndergraduate", "物理类".equals(subjectType) ? 448 : 456);
        }
        
        return scoreLines;
    }

    /**
     * 获取学生目标汇总
     */
    private TeacherDashboardRespVO.StudentGoalSummary getStudentGoalSummary(Long classId, Long examId) {
        TeacherDashboardRespVO.StudentGoalSummary summary = new TeacherDashboardRespVO.StudentGoalSummary();
        
        // 1. 获取参考学生ID列表
        List<ExamScoreDO> scores = examScoreMapper.selectList(new LambdaQueryWrapperX<ExamScoreDO>()
                .eq(ExamScoreDO::getExamId, examId)
                .eqIfPresent(ExamScoreDO::getClassId, classId));
        
        if (scores.isEmpty()) {
            return createDefaultStudentGoalSummary();
        }
        
        Set<Long> studentIds = scores.stream()
                .map(ExamScoreDO::getStudentId)
                .filter(Objects::nonNull)
                .collect(Collectors.toSet());
                
        if (studentIds.isEmpty()) {
            return createDefaultStudentGoalSummary();
        }
        
        // 2. 获取学生目标
        List<StudentMajorGroupGoalDO> goals = studentMajorGroupGoalService.getMajorGroupGoalList(studentIds);
        
        // 3. 统计设置目标的人数
        Set<Long> studentsWithGoals = goals.stream()
                .map(StudentMajorGroupGoalDO::getUserId)
                .collect(Collectors.toSet());
                
        int totalStudents = studentIds.size();
        int withGoalsCount = studentsWithGoals.size();
        
        summary.setTotalStudentsWithGoals(withGoalsCount);
        summary.setTotalStudentsWithoutGoals(totalStudents - withGoalsCount);
        
        // 4. 统计热门大学
        Map<String, Long> universityCount = goals.stream()
                .collect(Collectors.groupingBy(StudentMajorGroupGoalDO::getUniversityName, Collectors.counting()));
        
        List<TeacherDashboardRespVO.PopularUniversity> popularUniversities = universityCount.entrySet().stream()
                .sorted(Map.Entry.<String, Long>comparingByValue().reversed())
                .limit(5)
                .map(entry -> {
                    TeacherDashboardRespVO.PopularUniversity u = new TeacherDashboardRespVO.PopularUniversity();
                    u.setUniversityName(entry.getKey());
                    u.setCount(entry.getValue().intValue());
                    return u;
                })
                .collect(Collectors.toList());
        summary.setPopularUniversities(popularUniversities);
        
        // 5. 统计热门专业
        Map<String, Long> majorCount = goals.stream()
                .collect(Collectors.groupingBy(StudentMajorGroupGoalDO::getMajorGroupName, Collectors.counting()));
                
        List<TeacherDashboardRespVO.PopularMajor> popularMajors = majorCount.entrySet().stream()
                .sorted(Map.Entry.<String, Long>comparingByValue().reversed())
                .limit(5)
                .map(entry -> {
                    TeacherDashboardRespVO.PopularMajor m = new TeacherDashboardRespVO.PopularMajor();
                    m.setMajorName(entry.getKey());
                    m.setCount(entry.getValue().intValue());
                    return m;
                })
                .collect(Collectors.toList());
        summary.setPopularMajors(popularMajors);
        
        // 6. 计算目标完成率 (模拟：达到最低分数的比例)
        long reachedGoalCount = 0;
        
        // 预处理分数映射
        Map<Long, BigDecimal> studentScores = scores.stream()
                .filter(s -> s.getTotalScore() != null)
                .collect(Collectors.toMap(ExamScoreDO::getStudentId, ExamScoreDO::getTotalScore, (k1, k2) -> k1));
                
        for (Long studentId : studentsWithGoals) {
            BigDecimal currentScore = studentScores.get(studentId);
            if (currentScore == null) continue;
            
            // 获取该学生的所有目标
            boolean isReached = goals.stream()
                    .filter(g -> g.getUserId().equals(studentId))
                    .anyMatch(g -> g.getMinScore() != null && currentScore.compareTo(BigDecimal.valueOf(g.getMinScore())) >= 0);
            
            if (isReached) {
                reachedGoalCount++;
            }
        }
        
        if (withGoalsCount > 0) {
            summary.setGoalCompletionRate(BigDecimal.valueOf(reachedGoalCount * 100.0 / withGoalsCount).setScale(1, RoundingMode.HALF_UP));
        } else {
            summary.setGoalCompletionRate(BigDecimal.ZERO);
        }
        
        return summary;
    }

    private TeacherDashboardRespVO.StudentGoalSummary createDefaultStudentGoalSummary() {
        TeacherDashboardRespVO.StudentGoalSummary summary = new TeacherDashboardRespVO.StudentGoalSummary();
        summary.setTotalStudentsWithGoals(0);
        summary.setTotalStudentsWithoutGoals(0);
        summary.setGoalCompletionRate(BigDecimal.ZERO);
        summary.setPopularUniversities(new ArrayList<>());
        summary.setPopularMajors(new ArrayList<>());
        return summary;
    }

    /**
     * 获取目标指标分析
     */
    private TeacherDashboardRespVO.GoalIndicatorAnalysis getGoalIndicatorAnalysis(Long classId, Long examId) {
        TeacherDashboardRespVO.GoalIndicatorAnalysis analysis = new TeacherDashboardRespVO.GoalIndicatorAnalysis();
        
        // 1. 获取数据
        List<ExamScoreDO> scores = examScoreMapper.selectList(new LambdaQueryWrapperX<ExamScoreDO>()
                .eq(ExamScoreDO::getExamId, examId)
                .eqIfPresent(ExamScoreDO::getClassId, classId));
                
        if (scores.isEmpty()) {
            return createDefaultGoalIndicatorAnalysis();
        }
        
        Set<Long> studentIds = scores.stream()
                .map(ExamScoreDO::getStudentId)
                .filter(Objects::nonNull)
                .collect(Collectors.toSet());
        
        List<StudentMajorGroupGoalDO> goals = studentMajorGroupGoalService.getMajorGroupGoalList(studentIds);
        
        if (goals.isEmpty()) {
            return createDefaultGoalIndicatorAnalysis();
        }
        
        Map<Long, BigDecimal> studentScores = scores.stream()
                .filter(s -> s.getTotalScore() != null)
                .collect(Collectors.toMap(ExamScoreDO::getStudentId, ExamScoreDO::getTotalScore, (k1, k2) -> k1));
        
        // 2. 计算平均分差
        BigDecimal totalGap = BigDecimal.ZERO;
        int gapCount = 0;
        
        Map<String, Integer> statusDistribution = new HashMap<>();
        statusDistribution.put("安全", 0);
        statusDistribution.put("稳妥", 0);
        statusDistribution.put("冲刺", 0);
        statusDistribution.put("困难", 0);
        
        for (StudentMajorGroupGoalDO goal : goals) {
            BigDecimal currentScore = studentScores.get(goal.getUserId());
            if (currentScore != null && goal.getMinScore() != null) {
                BigDecimal goalScore = BigDecimal.valueOf(goal.getMinScore());
                BigDecimal gap = currentScore.subtract(goalScore);
                
                totalGap = totalGap.add(gap);
                gapCount++;
                
                // 分布统计
                if (gap.compareTo(BigDecimal.valueOf(10)) >= 0) {
                    statusDistribution.put("安全", statusDistribution.get("安全") + 1);
                } else if (gap.compareTo(BigDecimal.ZERO) >= 0) {
                    statusDistribution.put("稳妥", statusDistribution.get("稳妥") + 1);
                } else if (gap.compareTo(BigDecimal.valueOf(-20)) >= 0) {
                    statusDistribution.put("冲刺", statusDistribution.get("冲刺") + 1);
                } else {
                    statusDistribution.put("困难", statusDistribution.get("困难") + 1);
                }
            }
        }
        
        if (gapCount > 0) {
            analysis.setAvgScoreGap(totalGap.divide(BigDecimal.valueOf(gapCount), 1, RoundingMode.HALF_UP));
        } else {
            analysis.setAvgScoreGap(BigDecimal.ZERO);
        }
        
        analysis.setGoalStatusDistribution(statusDistribution);
        
        // 3. 难度系数 (模拟：冲刺和困难的比例)
        int hardCount = statusDistribution.get("冲刺") + statusDistribution.get("困难");
        if (gapCount > 0) {
            analysis.setDifficultyCoefficient(BigDecimal.valueOf((double) hardCount / gapCount).setScale(2, RoundingMode.HALF_UP));
        } else {
            analysis.setDifficultyCoefficient(BigDecimal.ZERO);
        }
        
        return analysis;
    }
    
    private TeacherDashboardRespVO.GoalIndicatorAnalysis createDefaultGoalIndicatorAnalysis() {
        TeacherDashboardRespVO.GoalIndicatorAnalysis analysis = new TeacherDashboardRespVO.GoalIndicatorAnalysis();
        analysis.setAvgScoreGap(BigDecimal.ZERO);
        analysis.setDifficultyCoefficient(BigDecimal.ZERO);
        Map<String, Integer> map = new HashMap<>();
        map.put("安全", 0);
        map.put("稳妥", 0);
        map.put("冲刺", 0);
        map.put("困难", 0);
        analysis.setGoalStatusDistribution(map);
        return analysis;
    }
}
